\documentclass[12pt]{article}
\usepackage{times}
\usepackage{graphicx}
\usepackage{sidecap}
\usepackage{wrapfig}
\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\baselinestretch}{1.2}
\newenvironment{mylisting}
{\begin{list}{}{\setlength{\leftmargin}{1em}}\item\scriptsize\bfseries}
{\end{list}}
\newenvironment{mylisting2}
{\begin{list}{}{\setlength{\leftmargin}{1em}}\item\scriptsize\bfseries}
{\end{list}}

%%% This file is Open Content

\begin{document}
	\textbf{{\Huge XMantaRay}}
{\center{Dec 29, 2011, 
	Johan Ceuppens, Theo D'Hondt - Vrije Universiteit Brussel}}
\\
{\large{\textbf{\center Abstract}}}
\\
\\
\section{\large Introduction}



\begin{mylisting}
\begin{verbatim}
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
// Written by Ch. Tronche (http://tronche.lri.fr:8000/)
// Copyright by the author. This is unmaintained, no-warranty free software. 
// Please use freely. It is appreciated (but by no means mandatory) to
// acknowledge the author's contribution. Thank you.
// Started on Thu Jun 26 23:29:03 1997

//
// Xlib tutorial: 2nd program
// Make a window appear on the screen and draw a line inside.
// If you don't understand this program, go to
// http://tronche.lri.fr:8000/gui/x/xlib-tutorial/2nd-program-anatomy.html
//

#include <X11/Xlib.h> // Every Xlib program must include this
#include <assert.h>   // I include this to test return values the lazy way
#include <unistd.h>   // So we got the profile for 10 seconds
#include <vector>
#include <iostream>
#include<cmath> 
#include <X11/Xlib.h>
#include <X11/xpm.h>
#include "raymanta/RayManta.h"
#include "raymanta/RayMantaRayTracer.h"
#include "raymanta/RayMantaPoint.h"
#include "raymanta/RayMantaPolygonModel.h"
#include "raymanta/RayMantaPixmapTextureModelRotate.h"
#include "raymanta/RayMantaSpiderModel.h"
#include "raymanta/RayMantaEngine.h"
#include "raymanta/RayMantaMatrix3.h"
#include "config.h"
#include "raymanta/WindowManager.h"
#include "raymanta/RayManta.h"
#include "raymanta/RayMantaWindow.h"

static Display *dpy;
static DisplayBase<Display **> dpyb;
static RayManta xmantaray(xmantaray, dpyb);

void init(Display **dpy, Window *w);
void print_usage();

int main(int argc, char*argv[])
{
//try {//main code block
	
	//Display *dpy = XOpenDisplay(NIL);
	dpy = XOpenDisplay(NIL);
	assert(dpy);
	dpyb = DisplayBase<Display **>(&dpy);
	xmantaray.init(dpyb);	
	if (argc > 1 && (std::string(argv[1]) == std::string("-h") 
		|| std::string(argv[1]) == std::string("-help")
		|| std::string(argv[1]) == std::string("--help"))) {
		print_usage();
		exit(0);
	}

	//FIXME us e a bridge
	//dpyb = DisplayBase<Display **>(&dpy);
	//xmantaray = RayManta(xmantaray, dpyb);

	int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
 	int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));
	
	Window w, titlebarw;
	XSetWindowAttributes attrib_create;
	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask | CWBackingPixel;

	attrib_create.background_pixmap = None;
	attrib_create.override_redirect = True;
	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;
	XSizeHints theSizeHints;
        XWMHints theWMHints;

	theWMHints.initial_state = NormalState;
        theWMHints.flags = StateHint;

        theSizeHints.flags = PPosition | PSize;
        theSizeHints.x = 0;//x;
        theSizeHints.y = 0;//y;
        theSizeHints.width = 800;//width;
        theSizeHints.height = 600;//height;

  	Window root_window = RootWindow(dpy, DefaultScreen(dpy));
  	int depth = DefaultDepth(dpy, DefaultScreen(dpy));
  	Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy));
	w = XCreateWindow(dpy, root_window, 40, 40, 
			800, 600,
			1, depth, InputOutput,
			visual, create_mask,
			&attrib_create);
        //XSetWMHints(dpy,w,&theWMHints);
        //XSetNormalHints(dpy,w,&theSizeHints);
  	titlebarw = XCreateWindow(dpy, root_window, 40, 20, 
				800, 20,
				1, depth, InputOutput,
				visual, create_mask,
				&attrib_create);
	XReparentWindow(dpy, titlebarw, w, 0, 0);
	RayMantaWindow raywindow(&dpy,w,titlebarw);

	XSelectInput(dpy, w, StructureNotifyMask);

	XMapWindow(dpy, titlebarw);
	XMapWindow(dpy, w);

	GC gc = XCreateGC(dpy, w, 0, NIL);

	XSetForeground(dpy, gc, whiteColor);
 
  	xmantaray.initwindow(&raywindow);

//	init(&dpy,&w);
        ray3d::PixmapTextureModelRotate pm3(dpyb.get_display(),&w,&gc,"./post.xpm",24,24);
        ray3d::SpiderModel pm4(dpyb.get_display(),&w,&gc,"./gradient.xpm",24,24);

	XEvent e;
  for (int k = 0; k < 100000; k++) {
	//NOTE: draw() is inside eventloop processor
	XFillRectangle(dpy, titlebarw, gc,0,0,800,20);
	XFillRectangle(dpy, w, gc,0,0,800,600);
	xmantaray.eventloop(xmantaray/*,&dpy*/,&e);
	pm3.draw(dpyb.get_display(), &w,200,200);
	pm4.draw(dpyb.get_display(), &w,100,100);
	XFlush(dpy);
  }
  sleep(20);

/*} catch (std::exception &e) {

	std::cout<<"main excepted - "<<e.what()<<std::endl;

}*/
}
/*
void init(Display **dpy, Window *w)
{
  Pixel back_pix, fore_pix;
  back_pix = GetColor(dpy,(char *)"red");
  fore_pix = GetColor(dpy,(char *)"red");
  
  unsigned long gc_mask = 0;
  gc_mask = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
  XGCValues values;
  values.foreground = fore_pix;
  values.background = back_pix;
  values.graphics_exposures = True;
  //values.function = GXcopy|GXand;
  values.line_width = 3;

  Pixel back_pix2, fore_pix2;
  back_pix2 = GetColor(dpy,(char *)"red");
  fore_pix2 = GetColor(dpy,(char *)"red");
  
  unsigned long gc_mask2 = 0;
  gc_mask2 = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
  XGCValues values2;
  values.foreground = fore_pix2;
  values.background = back_pix2;
  values.graphics_exposures = True;
  //values.function = GXcopy|GXand;
  values.line_width = 3;
}
*/
void print_usage()
{
	std::cout<<"\txmantaray [OPTIONS]\n"<<
		   "\t-cast : raytracer code init\n"<<
		   "\tno options : 3D framework\n"<<std::endl;
} 
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
// Written by Ch. Tronche (http://tronche.lri.fr:8000/)
// Copyright by the author. This is unmaintained, no-warranty free software. 
// Please use freely. It is appreciated (but by no means mandatory) to
// acknowledge the author's contribution. Thank you.
// Started on Thu Jun 26 23:29:03 1997

//
// Xlib tutorial: 2nd program
// Make a window appear on the screen and draw a line inside.
// If you don't understand this program, go to
// http://tronche.lri.fr:8000/gui/x/xlib-tutorial/2nd-program-anatomy.html
//

#include <X11/Xlib.h> // Every Xlib program must include this
#include <assert.h>   // I include this to test return values the lazy way
#include <unistd.h>   // So we got the profile for 10 seconds
#include <iostream>
#include<cmath> 
#include <X11/Xlib.h>
#include <X11/xpm.h>
#include "RayManta.h"
#include "RayMantaPoint.h"
#include "config.h"
#include "WindowManager.h"
#include "RayManta.h"
#include "RayMantaWindow.h"

RayManta pixie;

#define NIL (0)       // A name for the void pointer
int xx,yy,zz;
int main(int argc, char*argv[])
{
      // Open the display

      Display *dpy = XOpenDisplay(NIL);
      assert(dpy);

      // Get some colors

      int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
      int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));

      // Create the window
	
      Window w, titlebarw;
  XSetWindowAttributes attrib_create;
  unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  attrib_create.background_pixmap = None;
  attrib_create.override_redirect = True;
  attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;
XSizeHints theSizeHints;
        XWMHints theWMHints;


theWMHints.initial_state = NormalState;
        theWMHints.flags = StateHint;



        theSizeHints.flags = PPosition | PSize;
        theSizeHints.x = 0;//x;
        theSizeHints.y = 0;//y;
        theSizeHints.width = 320;//width;
        theSizeHints.height = 200;//height;




  w = XCreateWindow(pixie.getDisplay(), pixie.getRootWindow(), 40, 40, 
			320, 200,
			1, pixie.getDepth(), InputOutput,
			pixie.getVisual(), create_mask,
			&attrib_create);
        //XSetWMHints(dpy,w,&theWMHints);
        //XSetNormalHints(dpy,w,&theSizeHints);
	//w = RayMantaWindow().createTopLevelWindow(0,0,100,100,3,&w);
  //titlebarw = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 80, 80,320, 200, 0, blackColor, blackColor);
  titlebarw = XCreateWindow(pixie.getDisplay(), pixie.getRootWindow(), 40, 20, 
			320, 20,
			1, pixie.getDepth(), InputOutput,
			pixie.getVisual(), create_mask,
			&attrib_create);
  XReparentWindow(pixie.getDisplay(), titlebarw, w, 0, 0);
	//RayMantaWindow *rmw = new RayMantaWindow();
      RayMantaWindow raywindow(w,titlebarw);

      // We want to get MapNotify events

      XSelectInput(dpy, w, StructureNotifyMask);

      // "Map" the window (that is, make it appear on the screen)

      XMapWindow(dpy, titlebarw);
      XMapWindow(dpy, w);

      // Create a "Graphics Context"

      GC gc = XCreateGC(dpy, w, 0, NIL);

      // Tell the GC we draw using the white color

      XSetForeground(dpy, gc, whiteColor);

      // Wait for the MapNotify event
/*
      for(;;) {
	    XEvent e;
	    XNextEvent(dpy, &e);
	    if (e.type == MapNotify)
		  break;
      }
*/
      // Draw the line
      //raywindow.drawline(w, 0,0,70,70); 
      //XDrawLine(dpy, w, gc, 10, 60, 180, 20);
      // Send the "DrawLine" request to the server
//	raywindow.drawsphere(w);

  for (zz = 0; zz< 20; zz++) {
  for (xx = 0; xx < 20; xx++) {
  for (yy = 0; yy < 20; yy++) {
  pid_t pid, pid2 = -1;
  if ((pid = fork()) > 0) {
	if (pid == 0) {
  	if ((pid2 = fork()) > 0) {
		if (pid2 == 0) {
  			double r = 4;
  			Point s(xx*10,yy*10,zz*10);
  			Point center(10,10,10); 
  			Point v = s - center; 
  			Point d(1,1,0);
  			//double t = (2*v*d + std::sqrt(2*v*d-4(v*v-r*r))/2 
  			double discr = (v*d)*(v*d) - (v*v - r*r);
  			double t1 = - (v*d) - std::sqrt((v*d)*(v*d) - (v*v - r*r));
  			double t2 = - (v*d) + std::sqrt((v*d)*(v*d) - (v*v - r*r));

  			std::cout<< "--->"<<t1<<t2<<std::endl;

  			//if (discr >= 0) 
			{
      				GC gc = XCreateGC(dpy, w, 0, NIL);
  				//XDrawRectangle(dpy, w, gc, 0,0,t1,t2);
  				XDrawLine(dpy, w, gc, 0,0,t1,t2);
      				//XMapWindow(dpy, w);
			}
		}
	} else if (pid == 0) { 
		exit(0); 
	} else { 
		exit(0); 
	}
	} else {
		exit(0); 
	}
	}
	
  }
  }
  }
  pixie.set_windows(&raywindow);
  pixie.eventloop();
  XFlush(dpy);

      sleep(10);
}

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
// Written by Ch. Tronche (http://tronche.lri.fr:8000/)
// Copyright by the author. This is unmaintained, no-warranty free software. 
// Please use freely. It is appreciated (but by no means mandatory) to
// acknowledge the author's contribution. Thank you.
// Started on Thu Jun 26 23:29:03 1997

//
// Xlib tutorial: 2nd program
// Make a window appear on the screen and draw a line inside.
// If you don't understand this program, go to
// http://tronche.lri.fr:8000/gui/x/xlib-tutorial/2nd-program-anatomy.html
//

#include <X11/Xlib.h> // Every Xlib program must include this
#include <assert.h>   // I include this to test return values the lazy way
#include <unistd.h>   // So we got the profile for 10 seconds
#include <vector>
#include <iostream>
#include<cmath> 
#include <X11/Xlib.h>
#include <X11/xpm.h>
#include "raymanta/RayMantaProducerSystem.h"
#include "raymanta/RayMantaPoint.h"
#include "raymanta/RayMantaPolygonModel.h"
#include "raymanta/RayMantaEngine.h"
#include "raymanta/RayMantaMatrix3.h"
#include "config.h"
#include "raymanta/WindowManager.h"
#include "raymanta/RayManta.h"
#include "raymanta/RayMantaWindow.h"

static Display *dpy;
static DisplayBase<Display **> dpyb;
static RayMantaProducerSystem xmantaray(xmantaray, dpyb);

void init(Display **dpy, Window *w);
void print_usage();

int main(int argc, char*argv[])
{
//try {//main code block
	
	//Display *dpy = XOpenDisplay(NIL);
	dpy = XOpenDisplay(NIL);
	assert(dpy);
	dpyb = DisplayBase<Display **>(&dpy);
	//static_cast<RayManta>(xmantaray).init(dpyb);	
	xmantaray.init(dpyb);	
	if (argc > 1 && (std::string(argv[1]) == std::string("-h") 
		|| std::string(argv[1]) == std::string("-help")
		|| std::string(argv[1]) == std::string("--help"))) {
		print_usage();
		exit(0);
	}

	//FIXME us e a bridge
	//dpyb = DisplayBase<Display **>(&dpy);
	//xmantaray = RayMantaProducerSystem(static_cast<RayMantaProducerSystem&>(xmantaray), dpyb);

	int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
 	int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));
	
	Window w, titlebarw;
	XSetWindowAttributes attrib_create;
	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask | CWBackingPixel;

	attrib_create.background_pixmap = None;
	attrib_create.override_redirect = True;
	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;
	XSizeHints theSizeHints;
        XWMHints theWMHints;

	theWMHints.initial_state = NormalState;
        theWMHints.flags = StateHint;

        theSizeHints.flags = PPosition | PSize;
        theSizeHints.x = 0;//x;
        theSizeHints.y = 0;//y;
        theSizeHints.width = 800;//width;
        theSizeHints.height = 600;//height;

  	Window root_window = RootWindow(dpy, DefaultScreen(dpy));
  	int depth = DefaultDepth(dpy, DefaultScreen(dpy));
  	Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy));
	w = XCreateWindow(dpy, root_window, 40, 40, 
			800, 600,
			1, depth, InputOutput,
			visual, create_mask,
			&attrib_create);
        //XSetWMHints(dpy,w,&theWMHints);
        //XSetNormalHints(dpy,w,&theSizeHints);
  	titlebarw = XCreateWindow(dpy, root_window, 40, 20, 
				800, 20,
				1, depth, InputOutput,
				visual, create_mask,
				&attrib_create);
	XReparentWindow(dpy, titlebarw, w, 0, 0);
	RayMantaWindow raywindow(&dpy,w,titlebarw);

	XSelectInput(dpy, w, StructureNotifyMask);

	XMapWindow(dpy, titlebarw);
	XMapWindow(dpy, w);

	GC gc = XCreateGC(dpy, w, 0, NIL);

	XSetForeground(dpy, gc, whiteColor);
 
  	xmantaray.initwindow(&raywindow);

//	init(&dpy,&w);

	XEvent e;
  for (int k = 0; k < 100000; k++) {
	//NOTE: draw() is inside eventloop processor
	XFillRectangle(dpy, titlebarw, gc,0,0,800,20);
	XFillRectangle(dpy, w, gc,0,0,800,600);
	xmantaray.eventloop(/*xmantaray*//*,&dpy*//*,*/ &e);
	XFlush(dpy);
  }
  sleep(20);

/*} catch (std::exception &e) {

	std::cout<<"main excepted - "<<e.what()<<std::endl;

}*/
}
/*
void init(Display **dpy, Window *w)
{
  Pixel back_pix, fore_pix;
  back_pix = GetColor(dpy,(char *)"red");
  fore_pix = GetColor(dpy,(char *)"red");
  
  unsigned long gc_mask = 0;
  gc_mask = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
  XGCValues values;
  values.foreground = fore_pix;
  values.background = back_pix;
  values.graphics_exposures = True;
  //values.function = GXcopy|GXand;
  values.line_width = 3;

  Pixel back_pix2, fore_pix2;
  back_pix2 = GetColor(dpy,(char *)"red");
  fore_pix2 = GetColor(dpy,(char *)"red");
  
  unsigned long gc_mask2 = 0;
  gc_mask2 = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
  XGCValues values2;
  values.foreground = fore_pix2;
  values.background = back_pix2;
  values.graphics_exposures = True;
  //values.function = GXcopy|GXand;
  values.line_width = 3;
}
*/
void print_usage()
{
	std::cout<<"\txmantaray [OPTIONS]\n"<<
		   "\tno options : 3D graphics producer\n"<<std::endl;
} 
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
// Written by Ch. Tronche (http://tronche.lri.fr:8000/)
// Copyright by the author. This is unmaintained, no-warranty free software. 
// Please use freely. It is appreciated (but by no means mandatory) to
// acknowledge the author's contribution. Thank you.
// Started on Thu Jun 26 23:29:03 1997

//
// Xlib tutorial: 2nd program
// Make a window appear on the screen and draw a line inside.
// If you don't understand this program, go to
// http://tronche.lri.fr:8000/gui/x/xlib-tutorial/2nd-program-anatomy.html
//

#include <X11/Xlib.h> // Every Xlib program must include this
#include <assert.h>   // I include this to test return values the lazy way
#include <unistd.h>   // So we got the profile for 10 seconds
#include <iostream>
#include<cmath> 
#include <X11/Xlib.h>
#include <X11/xpm.h>
#include<pthread.h> 
#include "RayManta.h"
#include "RayMantaPoint.h"
#include "config.h"
#include "WindowManager.h"
#include "RayManta.h"
#include "RayMantaWindow.h"

RayManta pixie;

#define NIL (0)       // A name for the void pointer
Display *dpy;
int xx,yy,zz;	
Window w;

void *drawonce(void *arg) {
	double r = 4;
	Point s(xx*10,yy*10,zz*10);
  	Point center(10,10,10); 
  	Point v = s - center; 
  	Point d(1,1,0);
  	//double t = (2*v*d + std::sqrt(2*v*d-4(v*v-r*r))/2 
  	double discr = (v*d)*(v*d) - (v*v - r*r);
  	double t1 = - (v*d) - std::sqrt((v*d)*(v*d) - (v*v - r*r));
 	double t2 = - (v*d) + std::sqrt((v*d)*(v*d) - (v*v - r*r));

  	std::cout<< "--->"<<t1<<t2<<std::endl;

  	//if (discr >= 0) 
	{
      	GC gc = XCreateGC(dpy, w, 0, NIL);
  	//XDrawRectangle(dpy, w, gc, 0,0,t1,t2);
  	XDrawLine(dpy, w, gc, 0,0,t1,t2);
      	//XMapWindow(dpy, w);
	}
	return (void *)0;
}

int main(int argc, char*argv[])
{
      // Open the display

      dpy = XOpenDisplay(NIL);
      assert(dpy);

      // Get some colors

      int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
      int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));

      // Create the window
	
      Window titlebarw;
  XSetWindowAttributes attrib_create;
  unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  attrib_create.background_pixmap = None;
  attrib_create.override_redirect = True;
  attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;
XSizeHints theSizeHints;
        XWMHints theWMHints;


theWMHints.initial_state = NormalState;
        theWMHints.flags = StateHint;



        theSizeHints.flags = PPosition | PSize;
        theSizeHints.x = 0;//x;
        theSizeHints.y = 0;//y;
        theSizeHints.width = 320;//width;
        theSizeHints.height = 200;//height;




  w = XCreateWindow(pixie.getDisplay(), pixie.getRootWindow(), 40, 40, 
			320, 200,
			1, pixie.getDepth(), InputOutput,
			pixie.getVisual(), create_mask,
			&attrib_create);
        //XSetWMHints(dpy,w,&theWMHints);
        //XSetNormalHints(dpy,w,&theSizeHints);
	//w = RayMantaWindow().createTopLevelWindow(0,0,100,100,3,&w);
  //titlebarw = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 80, 80,320, 200, 0, blackColor, blackColor);
  titlebarw = XCreateWindow(pixie.getDisplay(), pixie.getRootWindow(), 40, 20, 
			320, 20,
			1, pixie.getDepth(), InputOutput,
			pixie.getVisual(), create_mask,
			&attrib_create);
  XReparentWindow(pixie.getDisplay(), titlebarw, w, 0, 0);
	//RayMantaWindow *rmw = new RayMantaWindow();
      RayMantaWindow raywindow(w,titlebarw);

      // We want to get MapNotify events

      XSelectInput(dpy, w, StructureNotifyMask);

      // "Map" the window (that is, make it appear on the screen)

      XMapWindow(dpy, titlebarw);
      XMapWindow(dpy, w);

      // Create a "Graphics Context"

      GC gc = XCreateGC(dpy, w, 0, NIL);

      // Tell the GC we draw using the white color

      XSetForeground(dpy, gc, whiteColor);

      // Wait for the MapNotify event
/*
      for(;;) {
	    XEvent e;
	    XNextEvent(dpy, &e);
	    if (e.type == MapNotify)
		  break;
      }
*/
      // Draw the line
      //raywindow.drawline(w, 0,0,70,70); 
      //XDrawLine(dpy, w, gc, 10, 60, 180, 20);
      // Send the "DrawLine" request to the server
//	raywindow.drawsphere(w);

  for (zz = 0; zz< 20; zz++) {
  for (xx = 0; xx < 20; xx++) {
  for (yy = 0; yy < 20; yy++) {
  pthread_t pid;
  pthread_create(&pid, NULL, drawonce, NULL);	
  }
  }
  }
  pixie.set_windows(&raywindow);
  pixie.eventloop();
  XFlush(dpy);

      sleep(10);
}

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
// Written by Ch. Tronche (http://tronche.lri.fr:8000/)
// Copyright by the author. This is unmaintained, no-warranty free software. 
// Please use freely. It is appreciated (but by no means mandatory) to
// acknowledge the author's contribution. Thank you.
// Started on Thu Jun 26 23:29:03 1997

//
// Xlib tutorial: 2nd program
// Make a window appear on the screen and draw a line inside.
// If you don't understand this program, go to
// http://tronche.lri.fr:8000/gui/x/xlib-tutorial/2nd-program-anatomy.html
//

#include <X11/Xlib.h> // Every Xlib program must include this
#include <assert.h>   // I include this to test return values the lazy way
#include <unistd.h>   // So we got the profile for 10 seconds
#include <vector>
#include <iostream>
#include<cmath> 
#include <X11/Xlib.h>
#include <X11/xpm.h>
#include "raymanta/RayMantaRayTracer.h"
#include "raymanta/RayMantaPoint.h"
#include "raymanta/RayMantaPolygonModel.h"
#include "raymanta/RayMantaEngine.h"
#include "raymanta/RayMantaMatrix3.h"
#include "config.h"
#include "raymanta/WindowManager.h"
#include "raymanta/RayManta.h"
#include "raymanta/RayMantaWindow.h"

static Display *dpy;
static DisplayBase<Display **> dpyb;
static RayMantaRayTracer xmantaray(xmantaray, dpyb);

void init(Display **dpy, Window *w);
void print_usage();

int main(int argc, char*argv[])
{
//try {//main code block
	
	//Display *dpy = XOpenDisplay(NIL);
	dpy = XOpenDisplay(NIL);
	assert(dpy);
	dpyb = DisplayBase<Display **>(&dpy);
	xmantaray.init(dpyb);	
	if (argc > 1 && (std::string(argv[1]) == std::string("-h") 
		|| std::string(argv[1]) == std::string("-help")
		|| std::string(argv[1]) == std::string("--help"))) {
		print_usage();
		exit(0);
	}

	//FIXME us e a bridge
	//dpyb = DisplayBase<Display **>(&dpy);
	//xmantaray = RayMantaRayTracer(static_cast<RayMantaRayTracer&>(xmantaray), dpyb);

	int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
 	int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));
	
	Window w, titlebarw;
	XSetWindowAttributes attrib_create;
	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask | CWBackingPixel;

	attrib_create.background_pixmap = None;
	attrib_create.override_redirect = True;
	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;
	XSizeHints theSizeHints;
        XWMHints theWMHints;

	theWMHints.initial_state = NormalState;
        theWMHints.flags = StateHint;

        theSizeHints.flags = PPosition | PSize;
        theSizeHints.x = 0;//x;
        theSizeHints.y = 0;//y;
        theSizeHints.width = 800;//width;
        theSizeHints.height = 600;//height;

  	Window root_window = RootWindow(dpy, DefaultScreen(dpy));
  	int depth = DefaultDepth(dpy, DefaultScreen(dpy));
  	Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy));
	w = XCreateWindow(dpy, root_window, 40, 40, 
			800, 600,
			1, depth, InputOutput,
			visual, create_mask,
			&attrib_create);
        //XSetWMHints(dpy,w,&theWMHints);
        //XSetNormalHints(dpy,w,&theSizeHints);
  	titlebarw = XCreateWindow(dpy, root_window, 40, 20, 
				800, 20,
				1, depth, InputOutput,
				visual, create_mask,
				&attrib_create);
	XReparentWindow(dpy, titlebarw, w, 0, 0);
	RayMantaWindow raywindow(&dpy,w,titlebarw);

	XSelectInput(dpy, w, StructureNotifyMask);

	XMapWindow(dpy, titlebarw);
	XMapWindow(dpy, w);

	GC gc = XCreateGC(dpy, w, 0, NIL);

	XSetForeground(dpy, gc, whiteColor);
 
  	xmantaray.initwindow(&raywindow);

//	init(&dpy,&w);

	XEvent e;
  for (int k = 0; k < 100000; k++) {
	//NOTE: draw() is inside eventloop processor
	//XFillRectangle(dpy, titlebarw, gc,0,0,800,20);
	//XFillRectangle(dpy, w, gc,0,0,800,600);
	xmantaray.eventloop(xmantaray/*,&dpy*/,&e);
	XFlush(dpy);
  }
  sleep(20);

/*} catch (std::exception &e) {

	std::cout<<"main excepted - "<<e.what()<<std::endl;

}*/
}
/*
void init(Display **dpy, Window *w)
{
  Pixel back_pix, fore_pix;
  back_pix = GetColor(dpy,(char *)"red");
  fore_pix = GetColor(dpy,(char *)"red");
  
  unsigned long gc_mask = 0;
  gc_mask = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
  XGCValues values;
  values.foreground = fore_pix;
  values.background = back_pix;
  values.graphics_exposures = True;
  //values.function = GXcopy|GXand;
  values.line_width = 3;

  Pixel back_pix2, fore_pix2;
  back_pix2 = GetColor(dpy,(char *)"red");
  fore_pix2 = GetColor(dpy,(char *)"red");
  
  unsigned long gc_mask2 = 0;
  gc_mask2 = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
  XGCValues values2;
  values.foreground = fore_pix2;
  values.background = back_pix2;
  values.graphics_exposures = True;
  //values.function = GXcopy|GXand;
  values.line_width = 3;
}
*/
void print_usage()
{
	std::cout<<"\txmantaray [OPTIONS]\n"<<
		   "\t-cast : raytracer code init\n"<<
		   "\tno options : 3D framework\n"<<std::endl;
} 
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _XLUACODE_H_
#define _XLUACODE_H_

#include "../include/lua.h"

namespace XLUA {
int luanetfork(lua_State *L);
int luamarkovnetfork(lua_State *L);
int luaxnetfork(lua_State *L);

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _XLUA_H_
#define _XLUA_H_
#include <string>
#include "../include/lua.h"
#include "../include/llex.h"
#include "../include/lauxlib.h"
//#include <lua.h>//FIXME1

namespace XLUA {

template <class S, class T>
class Xlua {
public:
	explicit Xlua() { L = NULL; init(); }
	virtual ~Xlua() { lua_close(L); }

	virtual int load();
	virtual int loadfile(S const& filename);
	virtual int loadstring(S const& s); 

protected:
	//lua interpreting load and call functions
	virtual int init();
protected:
	lua_State *L;
};

}
#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "xluacode.h"
#include<string>
#include<cstdio>

#include "../raymanta/RayMantaNet.h"
#include "../raymanta/RayMantaNetMarkov2.h"
#include "../raymanta/RayMantaXNet.h"

namespace XLUA {

int luanetfork(lua_State *L)
{
	std::string loadfilename, parsefilename;
	int kwl;
	int n = lua_gettop(L);
	if (n == 1 || n != 3) std::fprintf(stdout, "Do not fork.\t");
	if (lua_isstring(L,1)) loadfilename = lua_tostring(L,1);
	if (lua_isstring(L,2)) parsefilename = lua_tostring(L,2);
	if (lua_isnumber(L,3)) kwl = lua_tonumber(L,3);

	RayMantaNet<std::string,std::string> net;

	for (int i = 0; i < kwl; i++) {	
		///net.fork(std::string(loadfilename.c_str()), std::string(parsefilename.c_str()), i);
		net.fork();
	}

	return 0;

}

int luamarkovnetfork(lua_State *L)
{ 
	/*FIXME : 
	 * include RayMantaNetMarkov net; and do net.fork as above in
	 * the luanetfork procedure. 
	 * You can also coroutine the markovpropagate function code in lua's
	 * syntax : coroutine.create
	 */ 
	std::string loadfilename, parsefilename;
	int kwl;
	int n = lua_gettop(L);
	if (n == 1 || n != 3) fprintf(stdout, "Do not fork.\t");
	if (lua_isstring(L,1)) loadfilename = lua_tostring(L,1);
	if (lua_isstring(L,2)) parsefilename = lua_tostring(L,2);
	if (lua_isnumber(L,3)) kwl = lua_tonumber(L,3);

	RayMantaNetMarkov2<std::string,std::string> net;

	for (int i = 0; i < kwl; i++) {	
		///net.fork(std::string(loadfilename.c_str()), std::string(parsefilename.c_str()), i);
		net.fork();
	}


	return 0; 
}

int luaxnetfork(lua_State *L)
{ 
	/*FIXME : 
	 * include RayMantaNetMarkov net; and do net.fork as above in
	 * the luanetfork procedure. 
	 * You can also coroutine the markovpropagate function code in lua's
	 * syntax : coroutine.create
	 */ 
	std::string loadfilename("./loadfile"), parsefilename("./parsefile");
	int kwl;
	int n = lua_gettop(L);
	if (n == 1 || n != 3) fprintf(stdout, "Do not fork.\t");
	if (lua_isstring(L,1)) loadfilename = lua_tostring(L,1);
	if (lua_isstring(L,2)) parsefilename = lua_tostring(L,2);
	if (lua_isnumber(L,3)) kwl = lua_tonumber(L,3);

	RayMantaXNet<std::string,std::string> net;

	fprintf(stdout, "Forking for keywords in %s...\n",  parsefilename.c_str());
	for (int i = 0; i < kwl; i++) {	
		net.fork(std::string(loadfilename.c_str()), std::string(parsefilename.c_str()), i);//access e.g. with shared mem these forked processes
	}


	return 0; 
}

}

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "xlua.h"
#include "xluacode.h"
namespace XLUA {

template <class S, class T>
int Xlua<S,T>::init() {
	L = lua_open();
	return 0;
}

template<class S, class T>
int Xlua<S,T>::loadfile(S const& filename) { 
	luaL_loadfile(L,filename.c_str());
	return 0;
}

template<class S, class T>
int Xlua<S,T>::loadstring(S const& s) { 
	luaL_loadfile(L,s.c_str());
	return 0;
}
template <class S, class T>
int Xlua<S,T>::load()
{
	lua_register(L,"netfork",luanetfork);
	lua_register(L,"markovnetfork",luamarkovnetfork);
	lua_register(L,"xnetfork",luaxnetfork);
	//FIXME86 if (luaL_dofile(L,NULL)!=0) fprintf(stderr, "%s\n", lua_tostring(L,-1));
return 0;
}

}
ECHO=echo
CXX=g++
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=\
xlua.cpp \
xluacode.cpp

OBJECTS=$(SOURCES:.cpp=.o)
LIBRARY=libxlua.so


all: $(SOURCES) $(OBJECTS) $(LIBRARY)
	
clean:
	rm -f *.o *.so *.a

$(LIBRARY): $(OBJECTS) 
	@echo "***COMPILER NOTE*** if this fails repath liblua.so or liblua.a in the local Makefile"
	ar rcu libxlua.a *.o
	ranlib libxlua.a

.cpp.o:
	$(CXX) $(CFLAGS) $< -o $@
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BOLTZMAN_H_
#define _BOLTZMAN_H_
#include <vector>
#include "RayMantaMatrix.h"
#include <cmath>

typedef std::vector<double> Energies;
class Boltzman {
public:
	Boltzman(double n, double t = 10) { k = std::pow(1.3806502,-23); T = t; N = n; epsilon = 0.5; Z = std::exp(epsilon/k*t); }
	virtual ~Boltzman() {}
	
	inline double frandomepsilon() { /*epsilon = std::rand(); return std::exp(-epsilon/k*T);*/ }
	inline double f() { return std::exp(-epsilon/k*T); }
	//Boltzman statistics (2 functions)
	inline double f2(double N, Energies egs, double eps, double t); 
	inline double fz(double N, int i, Energies egs, double eps, double t); 
	virtual Matrix generateboltzmanmatrix(Boltzman const& b, int cols, int rows);

protected:
	double N,Z,k,T,epsilon;
};

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _KEYW_H_
#define _KEYW_H_

#include <vector>

template <class S, class T>
class KeyWords {
public:
	static std::vector<T> keywords;

public:
	//FIXME T& operator[](int index) { return keywords[index]; }
	T operator[](int index) { return keywords[index]; }
	int add(T t) { keywords.push_back(t); return 0; }
	int size() { return keywords.size(); }
};
template <class S, class T>
typename
std::vector<T> KeyWords<S,T>::keywords = std::vector<T>(); 

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __BASE_H_H
#define __BASE_H_H
#include <X11/Xlib.h>

struct RayMantaBase {
	virtual void eventloop(RayMantaBase&,XEvent *e) = 0;
  	virtual int process_event(XEvent *) = 0;
//derive	virtual void visit(DisplayBase<> dpyb) = 0; 
};
template <class T>
class DisplayBase {
public:
	DisplayBase() { dpy = NULL; }
	DisplayBase(T dpy2) { dpy = dpy2; }
	virtual ~DisplayBase() {}
	inline virtual T get_display() { return dpy; }
//derive	void accept(RayMantaBase rmb) { rmb.visit(this); }
protected:
	T dpy;
};

class RayMantaBaseVisit;
class DisplayBaseVisit : public DisplayBase<Display **> {

	virtual void accept(RayMantaBaseVisit& rmb);
};

struct RayMantaBaseVisit : public RayMantaBase {

	//virtual void draw
	virtual void visit(DisplayBase<Display **>& dpyb); 
};
	
#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYENGINE_H_
#define _RAYENGINE_H_
#include "RayMantaMatrix3.h"
#include<cmath>
#include<iostream>

namespace ray3d {

inline Matrix3 rotatex(double t1) {
	return (Matrix3(1,0,0,0,std::cos(t1),-std::sin(t1),0,std::sin(t1),std::cos(t1)));
}
inline Matrix3 rotatey(double t2) {
	return (Matrix3(std::cos(t2),0,std::sin(t2),0,1,0,-std::sin(t2),0,std::cos(t2)));
}
inline Matrix3 rotatez(double t3) {
	return (Matrix3(std::cos(t3),-std::sin(t3),0,std::sin(t3),std::cos(t3),0,0,0,1));
}
	
class Engine {
public:

	Engine() {}
	Engine(double t1, double t2, double t3) 
		: vtr(Vector3(1,1,1)),
		  mx(ray3d::rotatex(t1)),
		  my(ray3d::rotatey(t2)),
		  mz(ray3d::rotatez(t3)),
		  mtotal(mx*my*mz) {}
	virtual ~Engine() {}

	inline Matrix3 rotatex(double t) { theta1 = t; return ray3d::rotatex(t); }	
	inline Matrix3 rotatey(double t) { theta2 = t; return ray3d::rotatey(t); }	
	inline Matrix3 rotatez(double t) { theta3 = t; return ray3d::rotatez(t); }


	inline Vector3 translate(double t) { return vtr(t); }

	inline Matrix3 rotate (double t1,double t2,double t3) { 
		if (t1==theta1 && t2 == theta2 && t3 == theta3) 
			return mtotal;
		mtotal = initrotatex(t1)*initrotatey(t2)*initrotatez(t3); 
		return mtotal;
	}	
	inline Matrix3 rotate2(double t1,double t2,double t3) { 
		if (t1==theta1 && t2 == theta2 && t3 == theta3) 
			return mtotal;
		if (t1==theta1 && t2 == theta2) 
			return (mtotal = mx*my*initrotatez(t3)); 
		if (t1==theta1 && t3 == theta3) 
			return (mtotal = mx*initrotatey(t2)*mz); 
		if (t2==theta2 && t3 == theta3) 
			return (mtotal = initrotatex(t1)*my*mz); 
		if (t1==theta1) 
			return (mtotal = mx*initrotatey(t2)*initrotatez(t3)); 
		if (t2==theta2) 
			return (mtotal = initrotatex(t1)*my*initrotatez(t3)); 
		if (t3==theta3) 
			return (mtotal = initrotatex(t1)*initrotatey(t2)*mz); 
			
		return (mtotal = mx*my*mz);
		}
private:
	inline Matrix3 initrotatex(double t) { theta1 = t; return ray3d::rotatex(t); }	
	inline Matrix3 initrotatey(double t) { theta2 = t; return ray3d::rotatey(t); }	
	inline Matrix3 initrotatez(double t) { theta3 = t; return ray3d::rotatez(t); }

protected:	

	Vector3 vtr;
	double theta1,theta2,theta3;
	Matrix3 mx,my,mz,mtotal;
};
}
#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GA_H_
#define _GA_H_

#include <vector>
#include <cmath>

typedef std::vector<double > Genes;

class RayMantaGA {
public:
	RayMantaGA() {}
	RayMantaGA(int size) {/*FIXME linux for (int i = 0; i< size; i++) genes.push_back(std::rand());*/ }
//	inline void init(int size) { /* FIXME linux for (int i = 0; i< size; i++) genes.push_back(std::rand());*/ }
	RayMantaGA(Genes g) { genes = g; }
	virtual ~RayMantaGA() {}

	Genes mutate(int index);	
	Genes crossover(int index1, int index2, Genes g);	
	Genes crossover2(int index1, int index2, Genes g);	
	Genes crossoversame(int index1, int index2);	
	Genes crossoversame2(int index1, int index2);	

	Genes get_genes() { return genes; }


	int eventloop(int ngenes);

protected:
	double fitness();
	double fitness2();//inner product
	double fitness3();//linear programming
	double fitness4();//linear programming
 
	Genes genes;
	Genes crossovergenes;
};

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RAYMANTA_H
#define RAYMANTA_H
// libc 
#include <stdio.h>
#include <stdlib.h>
// X
#include <X11/Xlib.h>
//#include <Imlib.h>
//local
#include "Xmanager.h"
#include "WindowManager.h"
#include "RayMantaWindow.h"
#include "RayMantaImage.h"
#include "RayManta.rc"
#include "RayMantaBaseVisit.h"


class RayManta : public Xmanager , public WindowManager, public RayMantaBaseVisit
{
 private:
  RayMantaImage *background;
  
  //  void setBackground();
  //void foregroundWindows();
  void insert_window(RayMantaWindow *);
  RayMantaWindow *search_window(Window, bool);
  void erase_window(RayMantaWindow * win);
  bool pressed, motion;
  int dx, dy ,x ,y, init_x_root, init_y_root;
  short int window_type; //type of window that got event
 public:
  RayManta(RayMantaBase& rmb, DisplayBase<Display **>& dpyb2);
  virtual ~RayManta();
  virtual void init(DisplayBase<Display **>& dpyb2);
  virtual void initwindow(RayMantaWindow *);
  virtual Pixel GetColor(Display **dpy, char *name);
  virtual void eventloop(RayMantaBase& rmb,XEvent *e);
  virtual int process_event(XEvent *);
  virtual void positionWindow(Display **dpy, RayMantaWindow *);
  virtual int drawdish(Display **dpy, int const& k);
  virtual int draw(RayMantaBase& rmb);
  virtual int draw2(Display **dpy, int const& k);
  virtual int draw3(Display **dpy, int const& k);
  virtual int drawsphere(Display **dpy, int const& k);

protected: 
  RayMantaWindow *window; //window which got last event
  /*static*/ DisplayBase<Display **> dpyb;
}; // class RayManta 

//DisplayBase<Display *> RayManta::dpyb = DisplayBase<Display *>();

struct rect {int x,y,x_right,y_right,w,h,surface;};
int compare_x(const void *, const void *);
#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RAYIMAGEBASE_H
#define RAYIMAGEBASE_H

#include<X11/Xlib.h>
#include<X11/xpm.h>
#include<string>
//interface
class RayMantaImageBase {
public:

  virtual int draw(Display **dpy, Window *w, int xx, int yy) = 0;
  virtual int putpixel(int xx, int yy, unsigned long value) = 0;

protected:
  XImage *image;


}; //class RayMantaImage

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RAYIMAGE_H
#define RAYIMAGE_H

#include<X11/Xlib.h>
#include<X11/xpm.h>
#include<string>

#include "RayMantaImageBase.h"

class RayMantaImage : public RayMantaImageBase 
{
 public:
  RayMantaImage(Display **dpy);
  int init() { /*XInitImage(image);*/ return 0;}
  virtual ~RayMantaImage() {}

  virtual int draw(Display **dpy, Window *w, int xx, int yy);
  virtual int putpixel(int xx, int yy, unsigned long value);

protected:
  XImage *shape;


}; //class RayMantaPixmapImage

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYMANTA_MATRIX_3_H_
#define _RAYMANTA_MATRIX_3_H_

#include "RayMantaPoint.h" 

namespace ray3d {

class Vector3 : public Point
{
public:
	Vector3(){}
	Vector3(double xx, double yy, double zz) : Point(xx,yy,zz) {}
	virtual ~Vector3() {}
	Vector3(Vector3 const& v) { 
		x = const_cast<Vector3&>(v).get_x(); y = const_cast<Vector3&>(v).get_y(); y = const_cast<Vector3&>(v).get_z(); }

protected:

public:
	Vector3 operator()(double const& t) { x *= t; y *= t; y *= t; return *this; }
	double operator*(Vector3 const& v);
	Vector3 operator=(Vector3 const& v) { 
		x = const_cast<Vector3&>(v).get_x(); y = const_cast<Vector3&>(v).get_y(); y = const_cast<Vector3&>(v).get_z(); return *this; }
};

class Matrix3 {

public:
	Matrix3() {}
	Matrix3(Vector3 const& row1, Vector3 const& row2, Vector3 const& row3); 
	virtual ~Matrix3() {}

	Matrix3(double xx11,double xx12,double xx13,double xx21,double xx22,double xx23,double xx31,double xx32, double xx33) 
	: x11(xx11),
	  x12(xx12),
	  x13(xx13),
	  x21(xx21),
	  x22(xx22),
	  x23(xx23),
	  x31(xx31),
	  x32(xx32),
	  x33(xx33)
	{}

	double get_x11() { return x11; }
	double get_x12() { return x12; }
	double get_x13() { return x13; }
	double get_x21() { return x21; }
	double get_x22() { return x22; }
	double get_x23() { return x23; }
	double get_x31() { return x31; }
	double get_x32() { return x32; }
	double get_x33() { return x33; }

protected:
	double x11,x12,x13,x21,x22,x23,x31,x32,x33;
public:
	Matrix3 operator*(Matrix3 const& m);
	Vector3 operator*(Vector3 const& v);
};

} // namespace ray3d

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYMANTA_MATRIX_4_H_
#define _RAYMANTA_MATRIX_4_H_

#include "RayMantaMatrix3.h"

namespace ray3d {

class Vector4
{
public:
	Vector4(){}
	Vector4(Vector3 const& v, double tt) : x11(const_cast<Vector3&>(v).get_x()), x12(const_cast<Vector3&>(v).get_y()), x13(const_cast<Vector3&>(v).get_z()), x14(tt) {}
	Vector4(double xx, double yy, double zz, double tt) : x11(xx), x12(yy), x13(zz), x14(tt) {}
	virtual ~Vector4() {}
	Vector4(Vector4 const& v) { 
		x11 = const_cast<Vector4&>(v).get_x(); x12 = const_cast<Vector4&>(v).get_y(); x13 = const_cast<Vector4&>(v).get_z(); x14 = const_cast<Vector4&>(v).get_t(); }

	double get_x() { return x11; }
	double get_y() { return x12; }
	double get_z() { return x13; }
	double get_t() { return x14; }

protected:
	double x11,x12,x13,x14;

public:
	Vector4 operator()(double t) { x11 *= t; x12 *= t; x13 *= t; x14 *= t; return *this; }
	double operator*(Vector4 const& v);
	Vector4 operator=(Vector4 const& v) { 
		x11 = const_cast<Vector4&>(v).get_x(); x12 = const_cast<Vector4&>(v).get_y(); x13 = const_cast<Vector4&>(v).get_z(); x14 = const_cast<Vector4&>(v).get_t(); return *this; }
};

class Matrix4 {

public:
	Matrix4() {}
	Matrix4(Vector4 const& row1, Vector4 const& row2, Vector4 const& row3, Vector4 const& row4); 
	virtual ~Matrix4() {}

	Matrix4(double xx11,double xx12,double xx13,double xx14,double xx21,double xx22,double xx23,double xx24,double xx31,double xx32, double xx33, double xx34, double xx41, double xx42, double xx43, double xx44) 
	{ 
	  x11 = xx11;
	  x12 = xx12;
	  x13 = xx13;
	  x14 = xx14;
	  x21 = xx21;
	  x22 = xx22;
	  x23 = xx23;
	  x24 = xx24;
	  x31 = xx31;
	  x32 = xx32;
	  x33 = xx33;
	  x34 = xx34;
	  x41 = xx41;
	  x42 = xx42;
	  x43 = xx43;
	  x44 = xx44;

	}

	double get_x11() { return x11; }
	double get_x12() { return x12; }
	double get_x13() { return x13; }
	double get_x14() { return x14; }
	double get_x21() { return x21; }
	double get_x22() { return x22; }
	double get_x23() { return x23; }
	double get_x24() { return x24; }
	double get_x31() { return x31; }
	double get_x32() { return x32; }
	double get_x33() { return x33; }
	double get_x34() { return x34; }
	double get_x41() { return x41; }
	double get_x42() { return x42; }
	double get_x43() { return x43; }
	double get_x44() { return x44; }

	Matrix4 project(double d) { return (Matrix4(1,0,0,0,
					0,1,0,0,
					0,0,1,0,
					0,0,1/d,0)); }

protected:
	double x11,x12,x13,x14,x21,x22,x23,x24,x31,x32,x33,x34,x41,x42,x43,x44;
public:
	Matrix4 operator*(Matrix4 const& m);
	Vector4 operator*(Vector4 const& v);
};

} // namespace ray3d

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYMANTA_MATRIX_H_
#define _RAYMANTA_MATRIX_H_
#include <vector>

typedef std::vector<double> PointsVector;
typedef std::vector<PointsVector> PointsMatrix;

class Vector
{
public:
	Vector(){}
	Vector(Vector const& v) { points = const_cast<Vector&>(v).get_points(); }
	Vector(PointsVector const& p){ points = p; }
	virtual ~Vector() {}

	PointsVector get_points() { return points; }
	void add(double d) { points.push_back(d); }
	double get(int index) { return points[index]; }
protected:
	PointsVector points;

public:
	double operator*(Vector const& v);
	Vector& operator=(Vector const& v) { points = const_cast<Vector&>(v).get_points(); return *this; } 
};

class Matrix {

public:
	Matrix() {}
	Matrix(Matrix const& m) { points = const_cast<Matrix&>(m).get_points(); }
	Matrix(PointsMatrix const& p){ points = p; }
	virtual ~Matrix() {}

	PointsMatrix get_points() { return points; }
	void add(PointsVector v) { points.push_back(v); }
	double get(int index, int index2) { return points[index][index2]; }

protected:
	PointsMatrix points;
public:
	Matrix operator*(Matrix const& m);
	Vector operator*(Vector const& v);
};

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYMODEL_H_
#define _RAYMODEL_H_
#include<string>
#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaEngine.h"

namespace ray3d {
// Model mixin class
//S = string class
//F = modelreader class
class Model {
public:
	#define NIL (0)
	Model (Display **dpy1, Window *w1, GC *gc1) { if (gc1 == NULL) gc = XCreateGC(*dpy1, *w, 0, NIL); else gc = *gc1; dpy = dpy1; w = w1;}
	virtual ~Model() {}

	virtual int filein(std::string const& filename);
	virtual int fileout(std::string const& filename);

	int rotatex(Engine const& engine, double t);
	int rotatey(Engine const& engine, double t);
	int rotatez(Engine const& engine, double t);
	int rotate(Engine const& engine, double t1, double t2, double t3);

	virtual int draw(Display **dpy, Window *w);
	virtual Display **get_dpy() { return dpy; }
	virtual Display **get_display() { return dpy; }
	virtual std::vector<Point> get_points() { return _points; }
	virtual Window *get_window() { return w; }
	virtual void addpoint(Point const& p) { _points.push_back(p); }
	virtual void empty_points() { _points = std::vector<Point>(1); }
	virtual void set_points(std::vector<Point> v) { _points = v; }
protected:
	std::vector<Point> _points;
	GC gc;
	Display **dpy;
	Window *w;
};

}

#endif
#ifndef _NETBASE_H_
#define _NETBASE_H_
#include <iostream>

#include <unistd.h>

class RayMantaNetBase
{
public:
	RayMantaNetBase() {}
	RayMantaNetBase(RayMantaNetBase const& n) {}
	virtual ~RayMantaNetBase() {}

	inline virtual int lock(pid_t pid) = 0; 
	inline virtual int get_status(pid_t pid) = 0; 
	inline virtual void set_status(pid_t pid, int s) = 0; 
public:	 
	RayMantaNetBase &operator=(RayMantaNetBase const& n) { return *this; }
};

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYNET_H_
#define _RAYNET_H_

#include <map>
#include <iostream>
#include <unistd.h>
#include "RayMantaNetBase.h"

template <class S, class T>
class RayMantaNet : public RayMantaNetBase
{
public:
	RayMantaNet() { _pgid = 256; }
	RayMantaNet(RayMantaNet const& n) { _scheduler = n._scheduler; _pgid = n._pgid; }
	virtual ~RayMantaNet() {}

	inline virtual int lock(pid_t pid) { _scheduler[pid] = -1; return 0; }
	inline virtual int get_status(pid_t pid) { return _scheduler[pid]; }
	inline virtual void set_status(pid_t pid, int s) { _scheduler[pid] = s; }

	
protected:
	//The following map can be used in reverse at the same time of the
	//transverse, you can search for pids
	//or your own process integer i.e. you can put pids in it.
	//You can also put in pids multiple times for fast lookups and
	//extra process data, you will then have to search the whole map
	//for your pids/ints.
	static std::map<int, pid_t> _scheduler;
	pid_t _pgid;
public:

	virtual int fork();
	virtual int fork(S const& loadfilename, S const& parsefilename, int const& wordid);
	virtual int waitforall();

	virtual int markovpropagate();

public:
	RayMantaNet &operator=(RayMantaNet const& n) { _scheduler = n._scheduler; _pgid = n._pgid; return *this; }
};

template <class S, class T>
typename
std::map<int, pid_t> RayMantaNet<S,T>::_scheduler = std::map<int,pid_t>(); 

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MARKOV2NET_H_
#define _MARKOV2NET_H_

#include <map>
#include <iostream>
#include <unistd.h>
#include "RayMantaNetBase.h"
#include "RayMantaMatrix.h"

template <class S, class T>
class RayMantaNetMarkov2 : public RayMantaNetBase
{
public:
	RayMantaNetMarkov2() { _pgid = 256; }
	RayMantaNetMarkov2(RayMantaNetMarkov2 const& n) { _scheduler = n._scheduler; _pgid = n._pgid; }
	virtual ~RayMantaNetMarkov2() {}

	inline virtual int lock(pid_t pid) { _scheduler[pid] = -1; return 0; }
	inline virtual int get_status(pid_t pid) { return _scheduler[pid]; }
	inline virtual void set_status(pid_t pid, int s) { _scheduler[pid] = s; }

	
private:
	//The following map can be used in reverse at the same time of the
	//transverse, you can search for pids
	//or your own process integer i.e. you can put pids in it.
	//You can also put in pids multiple times for fast lookups and
	//extra process data, you will then have to search the whole map
	//for your pids/ints.
	static std::map<int, pid_t> _scheduler;
	pid_t _pgid;
public:

	virtual int fork();
	virtual int waitforall();

	virtual int markovpropagate(Matrix const& m);
	virtual int markovtest(double d, pid_t pid);

public:
	RayMantaNetMarkov2 &operator=(RayMantaNetMarkov2 const& n) { _scheduler = n._scheduler; _pgid = n._pgid; return *this; }
};

template <class S, class T>
typename
std::map<int, pid_t> RayMantaNetMarkov2<S,T>::_scheduler = std::map<int,pid_t>(); 

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MARKOVNET_H_
#define _MARKOVNET_H_

#include <map>
#include <iostream>
#include <cmath>
#include <unistd.h>
#include "RayMantaNet.h"
#include "RayMantaMatrix.h"
#include "Boltzman.h"

template <class S, class T>
class RayMantaNetMarkov : public RayMantaNet<S,T>
{
public:
	RayMantaNetMarkov() {}
	virtual ~RayMantaNetMarkov() {}
	
public:

	virtual int markovpropagate(Matrix const& m);
	virtual int markovtest(double d, pid_t pid);
	virtual Matrix generateboltzmanmatrix(Boltzman const& b, int cols, int rows);
};


#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _NETPTHREAD_H_
#define _NETPTHREAD_H_

#include <map>
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include "RayMantaNetBase.h"

template <class S, class T>
class RayMantaNetPthread : public RayMantaNetBase
{
public:
	RayMantaNetPthread() {}
	RayMantaNetPthread(RayMantaNetPthread const& n) { this->_scheduler = n._scheduler; }
	virtual ~RayMantaNetPthread() {}

	inline virtual int lock(pthread_t pid) { return 0; }
	inline virtual int get_status(int pid) { return 0; }
	inline virtual void set_status(int pid, int s) {}

	
private:
	static std::map<int, pthread_t> _scheduler;

public:

	virtual int fork(S const& loadfilename, S const& parsefilename, int const& wordid);
//	virtual int parse(Parser<S,T> parser);
	virtual int waitforall();
public:
	RayMantaNetPthread &operator=(RayMantaNetPthread const& n) { _scheduler = n._scheduler; return *this; }
};

template <class S, class T>
typename
std::map<int, pthread_t> RayMantaNetPthread<S,T>::_scheduler = std::map<int, pthread_t>(); 

#endif
#ifndef RAYPIXMAPIMAGE_H
#define RAYPIXMAPIMAGE_H

#include<X11/Xlib.h>
#include<X11/xpm.h>
#include<string>

#include "RayMantaImageBase.h"

class RayMantaPixmapImage : public RayMantaImageBase 
{
 public:
  RayMantaPixmapImage();
  RayMantaPixmapImage(Display **dpy, std::string const& filename);
  int init() { XInitImage(image); return 0;}
  ~RayMantaPixmapImage();

  virtual int draw(Display **dpy, Window *w, int xx, int yy);
  virtual int putpixel(int xx, int yy, unsigned long value);
  virtual unsigned long getpixel(int xx, int yy);

protected:
  XImage *shape;


}; //class RayMantaPixmapImage

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYPIXMAPTEXTURE_H_
#define _RAYPIXMAPTEXTURE_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaEngine.h"
#include "RayMantaTexture.h"

namespace ray3d {

typedef std::vector<Texture> TextureVector;
class PixmapTextureModel;

class PixmapTexture : public Texture {
public:
	PixmapTexture (Display **dpy, std::string const& filename, double alpha, double beta, double gamma, int w, int h) : Texture(alpha,beta,gamma), _xpmimage(dpy, filename),_w(w),_h(h),_enlargew(w+w*h*alpha),_enlargeh(h+w*h*beta) {}
	virtual ~PixmapTexture() {}

	virtual int initdraw(PixmapTextureModel& model);
	virtual int rotatemodel(PixmapTextureModel& model);

	virtual int drawsmaller(Display **dpy, Window *w, int offsetx, int offsety, double a, double b);
	virtual int draw3(Display **dpy, Window *w);
	virtual int draw2(Display **dpy, Window *w);
	virtual int drawmain(Display **dpy, Window *w, int offsetx, int offsety);
	virtual int drawcurved(Display **dpy, Window *w,int offsetx, int offsety);
	virtual int drawcurved2(Display **dpy, Window *w,int offsetx, int offsety);
	virtual int drawcurved3(Display **dpy, Window *w,int offsetx, int offsety);
	virtual int drawbig(Display **dpy, Window *w, int offsetx, int offsety);
	virtual int drawbigger(Display **dpy, Window *w, int offsetx, int offsety);
	virtual int drawbiggerandrotate(Display **dpy, Window *w, int offsetx, int offsety);
	//virtual int drawbiggerandrotatemodel(PixmapTextureModel& model);
	virtual int drawenlargeandrotate(Display **dpy, Window *w, int offsetx, int offsety);
	virtual int drawenlargeandrotate2(Display **dpy, Window *w, int offsetx, int offsety);
	virtual int drawsmall(Display **dpy, Window *w, int offsetx, int offsety);
	virtual int drawsmallandrotate(Display **dpy, Window *w, int offsetx, int offsety);
	virtual RayMantaPixmapImage get_xpmimage() { return _xpmimage; }
	virtual int get_w() { return _w; }
	virtual int get_h() { return _h; }
protected:

	virtual int initdraw1(PixmapTextureModel& model);

	RayMantaPixmapImage _xpmimage;
	int _w,_h;	
	int _enlargew,_enlargeh;

	double thetax,thetay,thetaz;
};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYPIXMAPTEXTUREMODELFILL_H_
#define _RAYPIXMAPTEXTUREMODELFILL_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaEngine.h"
#include "RayMantaPixmapTextureModel.h"
#include "RayMantaPixmapTexture.h"
#include "RayMantaTexture.h"

namespace ray3d {
class PixmapTextureModelFill : public PixmapTextureModel {
public:
	PixmapTextureModelFill (Display **dpy, Window *w, GC *gc1, std::string const& filename,int ww, int hh) : PixmapTextureModel(dpy,w,gc1,filename,ww,hh) {}
	virtual ~PixmapTextureModelFill() {}

	virtual int draw(Display **dpy, Window *w);

protected:

};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYPIXMAPTEXTUREMODEL_H_
#define _RAYPIXMAPTEXTUREMODEL_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaEngine.h"
#include "RayMantaTextureModel.h"
#include "RayMantaPixmapTexture.h"
#include "RayMantaTexture.h"

namespace ray3d {
class PixmapTextureModel : public TextureModel {
public:
	PixmapTextureModel (Display **dpy, Window *w, GC *gc1, std::string const& filename,int ww, int hh) : TextureModel(dpy,w,gc1), _pixmaptexture(dpy, filename,1,1,1,ww,hh) {}
	virtual ~PixmapTextureModel() {}

	virtual int draw(Display **dpy, Window *w, int offsetx, int offsety);
	virtual int draw2(Display **dpy, Window *w);

protected:
	PixmapTexture _pixmaptexture;
	
};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYPIXMAPTEXTUREMODELROT_H_
#define _RAYPIXMAPTEXTUREMODELROT_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaEngine.h"
#include "RayMantaPixmapTextureModel.h"
#include "RayMantaPixmapTexture.h"
#include "RayMantaTexture.h"

namespace ray3d {
class PixmapTextureModelRotate : public PixmapTextureModel {
public:
	PixmapTextureModelRotate (Display **dpy, Window *w, GC *gc1, std::string const& filename,int ww, int hh) : PixmapTextureModel(dpy,w,gc1,filename,ww,hh) { _pixmaptexture.initdraw(*this); }
	virtual ~PixmapTextureModelRotate() {}

	virtual int draw(Display **dpy, Window *w, int offsetx, int offsety);

};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _POINT_H_
#define _POINT_H_
#include<cmath>
#include<iostream>
namespace ray3d {

class Point
{
public:
	Point(){}
	Point(double xx, double yy, double zz, unsigned long color) : x(xx),y(yy),z(zz),c(color) {}
	Point(double xx, double yy, double zz) : x(xx),y(yy),z(zz) {}
	virtual ~Point(){}

	double operator*(Point const&p) { return (const_cast<Point&>(p).x*x+const_cast<Point&>(p).y*y+const_cast<Point&>(p).z*z); }
	//double operator*(int const&p) { return (const_cast<Point&>(p).x*+const_cast<Point&>(p).y*y+const_cast<Point&>(p).z*z); }
	Point operator-(Point const&p) { return Point(const_cast<Point&>(p).x-x,const_cast<Point&>(p).y-y,const_cast<Point&>(p).z-z); }
	Point operator+(Point const&p) { return Point(const_cast<Point&>(p).x+x,const_cast<Point&>(p).y+y,const_cast<Point&>(p).z+z); }
	bool operator==(Point const&p) { return (x==const_cast<Point&>(p).x&&y==const_cast<Point&>(p).y&&z==const_cast<Point&>(p).z); }
	Point scale(int i) { x*=i; y*=i; z*=i; return *this; }
	Point scalex(int i) { x*=i; return *this; }
	Point scaley(int i) { y*=i; return *this; }
	Point scalez(int i) { z*=i; return *this; }
	Point operator=(Point const&p) { return Point(const_cast<Point&>(p).x+x,const_cast<Point&>(p).y+y,const_cast<Point&>(p).z+z); }
	double operator[](int index) { if (index == 0) return x; if (index == 1) return y; if (index == 2) return z; if (index == 3) return c; if (index > 3) return -1;  }

	Point operator()(double const& t) { x *= t; y *= t; z *= t; return *this; }
	double get_x() {return x;}
	double get_y() {return y;}
	double get_z() {return z;}
	double get_c() {return c;}//return color
	double get_color() {return c;}//return color
	double dist(Point const& p)
	{
		return (std::sqrt((get_x()-const_cast<Point&>(p).get_x()) * 
				(get_x()-const_cast<Point&>(p).get_x()) +
				(get_y()-const_cast<Point&>(p).get_y()) *
				(get_z()-const_cast<Point&>(p).get_z()) +
				(get_z()-const_cast<Point&>(p).get_z())));
	}
	int sqr(Point const& p)
	{
		x = get_x()*const_cast<Point&>(p).get_x(); y = get_y()*const_cast<Point&>(p).get_y(); z = get_z()*const_cast<Point&>(p).get_z();
		return 0;
	}
	Point normalize() { 
		double xx = x; 
		xx /= x*x+y*y+z*z;
		double yy = y; 
		yy /= x*x+y*y+z*z;
		double zz = z; 
		zz /= x*x+y*y+z*z;
		x = xx; y = yy; z = zz;
	}
protected:
	double x,y,z;
	unsigned long c;//color
};
}
#endif

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAY_POLYGON_H_
#define _RAY_POLYGON_H_
#include <vector>
#include "RayMantaPoint.h"
#include <X11/Xlib.h>

namespace ray3d {

typedef std::vector<Point> PolygonPoints;

class Polygon {
public:
	Polygon() : _points() {}
	Polygon(PolygonPoints const& v) : _points(v) {}
	virtual ~Polygon() {}

	virtual int draw(Display **dpy, Window *w);
	virtual void add(Point const& p) { _points.push_back(p); }
	virtual int size() { return _points.size(); }
protected:
	PolygonPoints _points;

	

public:
	Polygon operator+(Point const& p) { _points.push_back(p); return *this; }
	Polygon operator+=(Point const& p) { _points.push_back(p); return *this; }
	void operator-(Point const& p) { for (PolygonPoints::iterator vi = _points.begin(); vi != _points.end(); vi++) { if ((*vi) == p) { _points.erase(vi); break; }  } }
	Polygon operator=(Point const& p) { _points.push_back(p); return *this; }
	Point operator[](int index) { return _points[index]; }

};
}
#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYPOLYGONMODEL_H_
#define _RAYPOLYGONMODEL_H_

#include<X11/Xlib.h>
#include<vector>
#include<string>
#include "RayMantaPoint.h"
#include "RayMantaModel.h"
#include "RayMantaPolygon.h"

namespace ray3d {
// Model mixin class
typedef std::vector<Polygon> PolygonVector;
typedef std::vector<Point> PointVector;
class PolygonModel : public Model {
public:
	PolygonModel (Display **dpy, Window *w, GC *gc1) : Model(dpy,w,gc1) {}
	virtual ~PolygonModel() {}

	virtual int draw(Display **dpy, Window *w);
	virtual int raytrace(Display **dpy, Window *w);
	virtual int dithersunray(Display **dpy, Window *w);
	virtual void add(Polygon const& p) { _polygons.push_back(p); }

	virtual int filein(std::string const& filename);
	virtual int fileout(std::string const& filename);

protected:
	//NOTE: there is a _points vector in the base class
	PolygonVector _polygons;
public:
	Polygon operator+(Polygon p) { _polygons.push_back(p); return p; }
	PolygonModel operator+=(Polygon p) { _polygons.push_back(p); return *this; }
};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _OSYSTEM_H_
#define _OSYSTEM_H_

#include <vector>
#include <cmath>
#include "RayManta.h"
#include "RayMantaGA.h"

typedef std::vector<double > Genes;
#define SCREENW 800
#define SCREENH 600

class RayMantaProducerSystem : public RayMantaGA, public RayManta  {
public:
  	RayMantaProducerSystem(RayMantaBase& rmb,DisplayBase<Display **>& dpyb2) : RayManta(rmb,dpyb2)
	{ 
		genes.reserve(SCREENW*SCREENH);
		for (int i = 0; i < SCREENW*SCREENH /*genes.size()*/; i++) {

			genes[i] = (::rand());

		}
	}
	virtual ~RayMantaProducerSystem() {}
	//run once and get_genes afterwards for screen plot
	virtual Genes initcrossovergenes(int n);
	virtual Genes mutate(int index);
	virtual Genes crossover(int index1, int index2);
  	virtual int draw(RayMantaBase const& rmb);
  	virtual void eventloop(XEvent *e); 

protected:
};

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RAYMANTARYTR_H
#define RAYMANTARAYTR_H
// libc 
#include <stdio.h>
#include <stdlib.h>
// X
#include <X11/Xlib.h>
//#include <Imlib.h>
//local
#include "RayManta.h"
#include "RayManta.rc"

class RayMantaRayTracer : public RayManta 
{
 private:
 public:
  RayMantaRayTracer(RayMantaBase& rmb,DisplayBase<Display **>& dpyb2) : RayManta(rmb,dpyb2) {}
 // RayMantaRayTracer(Display **dpy, RayMantaWindow *rayw) : RayManta(dpy) { init(rayw); }
  virtual ~RayMantaRayTracer() {};
  virtual int draw(RayMantaBase const& rmb);
  virtual int draw2(Display **dpy, int const& k);
  virtual void eventloop(RayMantaBase& rmb, XEvent *e); 
}; // class RayManta 

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYSPHEREMODEL_H_
#define _RAYSPHEREMODEL_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaEngine.h"
#include "RayMantaModel.h"

namespace ray3d {

//S = string class
//F = modelreader class
class SphereModel : public Model {
public:
	SphereModel (Display **dpy, Window *w, GC *gc1) : Model(dpy,w,gc1) {}
	virtual ~SphereModel() {}

	int generatesphere(Display **dpy, Window *w);
	virtual int raycast(Display **dpy, Window *w);
	virtual int raytrace(Display **dpy, Window *w, Point const& p);
	virtual int raytrace2(Display **dpy, Window *w, Point const& p);
	virtual int dithersunray(Display **dpy, Window *w);
	virtual int drawsunray(Display **dpy, Window *w);

	virtual int draw(Display **dpy, Window *w);

protected: 
	//NOTE : The base class contains identical _points vector
	// Thisi e.g. is for circumference and Volume 
	std::vector<Point> _spherepoints;
};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYPIXMAPTEXTUREMODELSPIDER_H_
#define _RAYPIXMAPTEXTUREMODELSPIDER_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaEngine.h"
#include "RayMantaPixmapTextureModel.h"
#include "RayMantaSpiderTexture.h"
#include "RayMantaTexture.h"

namespace ray3d {
class SpiderModel : public PixmapTextureModel {
public:
	SpiderModel (Display **dpy, Window *w, GC *gc1, std::string const& filename,int ww, int hh) : PixmapTextureModel(dpy,w,gc1,filename,ww,hh), _spidertexture(dpy,filename,1,1,1,ww,hh) { 	_spidertexture.initdraw(*this); }
	virtual ~SpiderModel() {}

	virtual int draw(Display **dpy, Window *w, int offsetx, int offsety);
protected:
	SpiderTexture _spidertexture;
};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYSPIDERTEXTURE_H_
#define _RAYSPIDERTEXTURE_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaEngine.h"
#include "RayMantaPixmapTexture.h"

namespace ray3d {

class SpiderModel;

class SpiderTexture : public PixmapTexture {
public:
	SpiderTexture (Display **dpy, std::string const& filename, double alpha, double beta, double gamma, int w, int h) : PixmapTexture(dpy,filename,alpha,beta,gamma,w,h),_legw(80),_legh(60),_legz(10) {}
	virtual ~SpiderTexture() {}

	virtual int initdraw(SpiderModel& model);
	//diagonal spider leg (can be filed out)
	virtual int initspiderleg(SpiderModel& model);

	//clyndrical primitives and ditherings
	virtual int initclover(SpiderModel& model);
	//virtual int initconeorcylinderY(SpiderModel& model);
	virtual int initconeorcylindergrowY(SpiderModel& model);
	virtual int initconeorcylinderditherY(SpiderModel& model);
	virtual int initconeorcylinderdither2Y(SpiderModel& model);
	virtual int initconeorcylindersmallpatternY(SpiderModel& model);
	virtual int initconeorcylindersinkY(SpiderModel& model);
	virtual int initconeorcylindercurvedY(SpiderModel& model);
	virtual int rotatemodel(SpiderModel& model);

protected:

	virtual int initdraw1(SpiderModel& model);
	int _legw, _legh,_legz;
};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYTEXTURE_H_
#define _RAYTEXTURE_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaEngine.h"

namespace ray3d {
class Texture {
public:
	Texture (double alpha, double beta, double gamma) : _alpha(alpha),_beta(beta),_gamma(gamma) {}
	virtual ~Texture() {}

	virtual int draw(Display **dpy, Window *w);

	virtual double get_alpha() { return _alpha; }
	virtual double get_beta() { return _beta; }
	virtual double get_gamma() { return _gamma; }

protected:
	double _alpha,_beta,_gamma;//x,y,z scaling factors
};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYTEXTUREMODEL_H_
#define _RAYTEXTUREMODEL_H_

#include<X11/Xlib.h>
#include<vector>
#include "RayMantaPoint.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaEngine.h"
#include "RayMantaPolygonModel.h"

namespace ray3d {

class TextureModel : public PolygonModel {
public:
	TextureModel (Display **dpy, Window *w, GC *gc1) : PolygonModel(dpy,w,gc1) {}
	virtual ~TextureModel() {}

	virtual int draw(Display **dpy, Window *w);

};

}

#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RAYMWINDOW_H
#define RAYMWINDOW_H
//X
#include <X11/Xlib.h>
//local
#include "RayManta.h"
#include "RayMantaImage.h"

class RayMantaWindow {
 private:
  int title_y, lowerborder_y;
  Window window;
  GC gc;
  struct frame {
    Pixmap titlebar, destroy_button, lowerborder;
    int x, y, x_root, y_root;
    unsigned int  width, height, border_width;
    Window window, /*application_window,*/ title/*, destroy*/;
  } frame;
  bool created;
 protected:
  Window createChildWindow(Window parent, Cursor cursor);
  void decorate_title();
  Pixel GetColor(Display **dpy, char *name);
 public:
  void drawsphere(Window const& w);
  void drawline(Window const& w, int x1, int y1, int x2 ,int y2);
  //void drawline(int x1, int y1, int x2 ,int y2);
  Window createTopLevelWindow(int , int , unsigned int ,unsigned int ,unsigned int, Window *w);
  Window createTopLevelSimpleWindow(int x, int y, unsigned int width,unsigned int height,unsigned int borderwidth);
  RayMantaWindow();
  RayMantaWindow(Display **dpy, Window& , Window&);
  ~RayMantaWindow();
  inline Window getTitleWindow() { return frame.title; }
  inline Window getWindow() { return frame.window; }
  inline Window getClientWindow() { return window; }
  inline Window getLowerborderWindow() { return frame.lowerborder; }
//  inline Window getDestroyWindow() { return frame.destroy; }
  inline int getx() { return frame.x; }
  inline int gety() { return frame.y; }
  inline Window getWidth() { return frame.width; }
  inline Window getHeight() { return (frame.height+title_y+lowerborder_y); }
  void destroy(Display **dpy);
  void unmap(Display **dpy);
  void resize(Display **dpy, int, int);
  void configure(Display **dpy, XConfigureRequestEvent);
  void expose(XExposeEvent&);
  void buttonpress();
  void motion();
  void move(Display * *dpy, int ,int );
}; //class RayMantaWindow
#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _RAYXNET_H_
#define _RAYXNET_H_

#include <map>
#include <iostream>
#include <unistd.h>
#include "RayMantaNet.h"
#include "keywords.h"

template <class S, class T>
class RayMantaXNet : public RayMantaNet<S,T>
{
public:
	RayMantaXNet() : RayMantaNet<S,T>() { }
	virtual ~RayMantaXNet() {}

protected:
	KeyWords<S,T> keywords;
	virtual int loadXkeywords(KeyWords<S,T> const& kw);
public:

	virtual int addkeyword(T const& keyword) { keywords.add(keyword); return 0; }
	virtual int fork(S const& loadfilename, S const& parsefilename, int const& wordid);

};

#endif
#ifndef WINDOWMANAGER_H
#define WINDOWMANAGER_H
//libc
#include <stdio.h>
//X
#include <X11/Xlib.h>
//stl
#include <list>
//forward declarations
class RayMantaWindow;

class WindowManager {
 protected:
  std::list<RayMantaWindow *> windows;
  
 public:
  WindowManager();
  ~WindowManager();
}; //class WindowManager


#endif
#ifndef XMANAGER_H
#define XMANAGER_H

// libc 
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
// X
#include <X11/Xlib.h>
#include <X11/xpm.h>
class RayManta;
//extern RayManta pixie;
template <class D> class DisplayBase;
class Xmanager {
 protected:
  
  int depth, screen;
  Visual *visual;
  Window root_window;
  XFontSet fontset;

 public:
  Xmanager();
  void init(DisplayBase<Display * *>& dpyb);
  ~Xmanager();
  XFontSet createFontSet(DisplayBase<Display **>& dpyb);
  inline int getScreen() {return screen;}
  inline Window getRootWindow() { return root_window; }
  inline int getDepth() { return depth; }
  inline Visual *getVisual() { return visual; }
  inline XFontSet getFontSet() { return fontset; }
}; //class Xmanager

static const char *getFontElement(const char *pattern, char *buf, int bufsiz, ...);
static const char *getFontSize(const char *pattern, int *size);
#endif
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "Boltzman.h"

double Boltzman::fz(double N, int i, Energies egs, double eps, double t) { 

	double Zresult = 0;

	for (int j = 0; j < egs.size(); j++) {
		Zresult += egs[j]*std::exp(-eps/k*t);
	}
	return Zresult;
}

double Boltzman::f2(double N, Energies egs, double eps, double t) 
{
	double result = 0;
 
	for (int j = 0; j < egs.size(); j++) {
		result += N*egs[j]*std::exp(-eps/k*T)/fz(N, j, egs, eps, t);
	}

	return result; 
}
	
Matrix Boltzman::generateboltzmanmatrix(Boltzman const& b, int cols, int rows)
{

	Matrix m;
	Energies egs;
/*
	for (int k = 0; k < rows*cols; k++)
		egs.push_back(std::rand());
*/

	for (int i = 0; i < rows; i++){
		Vector v;
	for (int j = 0; j < cols; j++){
		
		v.add(const_cast<Boltzman&>(b).f2(rows*cols,egs,0.5,10));
	}
		m.add(v.get_points());
	}

	return m;

}

#include <string>
#include "keywords.h"

template class KeyWords<std::string, std::string>;
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaBaseVisit.h"

void DisplayBaseVisit::accept(RayMantaBaseVisit& rmb)
{ 
	rmb.visit(*this);
}

	//virtual void draw
void RayMantaBaseVisit::visit(DisplayBase<Display **>& dpyb) { 

	if (DisplayBaseVisit* rm = dynamic_cast<DisplayBaseVisit*>(&dpyb)) {
	//FIXME1	draw(*this);
	} else {
		return;
	} 
}

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "RayManta.h"
#include "RayMantaRayTracer.h"
#include "Xmanager.h"
#include "RayMantaWindow.h"
#include "RayMantaPoint.h"
#include "RayMantaEngine.h"
#include "RayMantaMatrix3.h"
#include "RayMantaPolygonModel.h"
#include "RayMantaSphereModel.h"
#include "RayMantaImage.h"
#include "RayMantaPixmapImage.h"
#include "RayMantaPixmapTextureModelRotate.h"


static double theta = 1.5;
static double theta2 = 2.5;
static double theta3 = 3.5;
int RayManta::draw2(Display **dpy, int const& k)
{
	Window w = window->getTitleWindow();
	Window w2 = window->getWindow(); 
//	RayMantaImage pix(dpyb->dpy);
//	pix.init();
//	pix.putpixel(10,10,12000);


      int blackColor = 128;//BlackPixel(dpyb->dpy, DefaultScreen(dpyb->dpy));
      int whiteColor = 2048;//WhitePixel(dpyb->dpy, DefaultScreen(dpyb->dpy));
	//blackColor <<= 8;
	//whiteColor <<= 16;

  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*(dpyb.get_display()),w,create_mask,&attrib_create);
	XGCValues values;
	values.foreground = 10400;//RedPixel(*(dpyb.get_display()), DefaultScreen(*(dpyb.get_display())));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), valuemask, &values);
	//3D rotation code
        ray3d::SphereModel sm(dpy,&w,&gc);
	//pix.draw(dpy, &w2,0,0);
	//XDrawLine(*(dpyb.get_display()), w2,gc, 0,0,100,100);
	sm.generatesphere(dpy, &w2);
	//sm.draw(dpy,&w2);
	sm.raytrace(dpy,&w2,ray3d::Point(0,0,0));
	return 0;
}

int RayManta::draw(RayMantaBase& rmb)
{
	Window w = window->getWindow(); 
        GC gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
	//3D rotation code
        ray3d::PolygonModel pm(dpyb.get_display(),&w,&gc);
        ray3d::PolygonModel pm2(dpyb.get_display(),&w,&gc);
        //ray3d::PixmapTextureModel pm3(dpyb.get_display(),&w,&gc,"./test640x480.xpm",640,480);
	ray3d::Polygon poly;

	poly += ray3d::Point(2,2,2);
	poly += ray3d::Point(120,120,120);
	poly += ray3d::Point(520,220,220);
	poly += ray3d::Point(2,2,2);
	pm.add(poly);
//	pm3.add(poly);

	pm2.filein("./polygonmodel");	

	pm.draw(dpyb.get_display(), &w);
	pm2.draw(dpyb.get_display(), &w);
//	pm3.draw(dpyb.get_display(), &w,200,200);
	//poly.draw(dpy, &w);
        ray3d::Vector3 v1(0,0,0), v2(100,100,100);
        ray3d::Matrix3 rotmx,rotmy,rotmz;
        //rotm = ray3d::Matrix3(e.initrotatex(0.1*k));
        rotmx = ray3d::rotatex(theta);
        rotmy = ray3d::rotatey(theta2);
        rotmz = ray3d::rotatez(theta3);

        v2 = rotmx*v2;
        v2 = rotmy*v2;
        v2 = rotmz*v2;
        //std::cout<<"matrix x22>"<<rotm.get_x22()<<std::endl;
        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,(int)v1.get_x(),(int)v1.get_y()+TITLEWINH,(int)v2.get_x(),(int)v2.get_y()+TITLEWINH);

	return 0;
}
//#include "widget/Button.h"
int RayManta::draw3(Display **dpy, int const& k)
{
	//3D rotation code
	theta *= 2;
	theta2 *= 3;
	theta3 *= 8;
        ray3d::Engine e(0.1,0.1,0.1);
        ray3d::Vector3 v1(10,10,10), v2(140,140,140);
	ray3d::Vector3 v3(140,140,140);
        ray3d::Matrix3 rotmx,rotmy,rotmz;
#define NIL (0)
        GC gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
        //rotm = ray3d::Matrix3(e.rotate(theta,theta2,theta3));
        rotmx = ray3d::rotatex(theta);
        rotmy = ray3d::rotatey(theta2);
        rotmz = ray3d::rotatez(theta3);

	v2 = rotmx*v3;	
	v2 = rotmy*v2;	
	v2 = rotmz*v2;	

        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,(int)(v3.get_x()),(int)(v3.get_y()),(int)(v2.get_x()),(int)(v2.get_y()));

	return 0;
}

int RayManta::drawsphere(Display **dpy, int const& k)
{
	Window w = window->getWindow(); 
        GC gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
	//3D rotation code
        ray3d::SphereModel sm(dpy,&w,&gc);

	sm.generatesphere(dpy, &w);
	sm.draw(dpy,&w);
/*        ray3d::Vector3 v1(0,0,0), v2(100,100,100);
        ray3d::Matrix3 rotmx,rotmy,rotmz;
        //rotm = ray3d::Matrix3(e.initrotatex(0.1*k));
        rotmx = ray3d::rotatex(theta1);
        rotmy = ray3d::rotatey(theta12);
        rotmz = ray3d::rotatez(theta13);

//        v2 = rotmx*v2;
//        v2 = rotmy*v2;
//        v2 = rotmz*v2;
        //std::cout<<"matrix x22>"<<rotm.get_x22()<<std::endl;
        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,0,0,100,100);
        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,(int)v1.get_x(),(int)v1.get_y(),(int)v2.get_x(),(int)v2.get_y());
*/
	return 0;
}

int RayManta::drawdish(Display **dpy, int const& k)
{
	//3D rotation code
	theta *= 2;
        ray3d::Engine e(0.1,0.1,0.1);
        ray3d::Vector3 v1(10,10,10), v2(140,140,140);
        ray3d::Matrix3 rotm;// = ray3d::Matrix3(e.rotate(0.1,0.1,0.1));
#define NIL (0)
        GC gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
        //rotm = ray3d::Matrix3(e.rotate(theta,theta,theta));
        rotm = ray3d::rotatex(theta);//ray3d::Matrix3(e.rotatex(3.1));

	ray3d::Vector3 v3(140,140,140);
	v2 = rotm*v3;	

        //v2 = rotm*v1;
        //ray3d::Vector3 v3 = rotm*v2;
        std::cout<<"matrix x22>"<<rotm.get_x22()<<std::endl;
        //std::cout<<"v3.x>"<<v3.get_x()<<std::endl;
	  //XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,0,0,100,100);
        //XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,(int)v1.get_x()*100,(int)v1.get_y()*100,(int)v2.get_x()*100,(int)v2.get_y()*100);
        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,(int)(v3.get_x()),(int)(v3.get_y()),(int)(v2.get_x()),(int)(v2.get_y()));


	return 0;
}

void RayManta::init(DisplayBase<Display **>& dpyb2)
{
	if (dpyb2.get_display() != NULL)
		dpyb = dpyb2;
}
	
RayManta::RayManta(RayMantaBase& rmb, DisplayBase<Display **>& dpyb2) : Xmanager(), WindowManager() , RayMantaBaseVisit() 
  //default :O display
{
	if (dpyb2.get_display() != NULL)
		dpyb = dpyb2;
		
  //::xmantaray= *this;
  pressed = False;
  motion = False;
  dx= dy = 0;
  window = (RayMantaWindow *) 0;
  unsigned long gc_mask = 0;
  gc_mask = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
  Pixel back_pix, fore_pix;
//  back_pix = GetColor(*(dpyb.get_display()),(char *)"blue");
//  fore_pix = GetColor(*(dpyb.get_display()),(char *)"lightblue");
/*
  XGCValues values;
  values.foreground = fore_pix;
  values.background = back_pix;
  values.graphics_exposures = True;
  //values.function = GXcopy|GXand;
  values.line_width = 3;
  GC gc = XCreateGC(*(dpyb.get_display()), getRootWindow(), gc_mask, &values);
*/
  //XSetFillStyle(*(dpyb.get_display()), gc, FillSolid);
//  XSetClipOrigin(*(dpyb.get_display()), gc, 0, 0);
//  XSetClipMask(*(dpyb.get_display()), gc, None);
  
  //  setBackground();
  //foregroundWindows();
  printf("made XMantaRay Server\n");
}

RayManta::~RayManta() {}

void RayManta::initwindow(RayMantaWindow *w) 
{
  	fontset = createFontSet(dpyb);
	window = w;	
}

void RayManta::eventloop(RayMantaBase& rmb, XEvent *e) 
{
  #define NIL (0)
  int events;
  GC gc;
  gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
  const char * test = "XMantaRay - 3D framework";
  XmbDrawString(*(dpyb.get_display()), window->getTitleWindow(), fontset, gc, 20, 10, test, strlen(test));
  draw(*this);
  
  for (int i = 0; i < 1000; i++) {//calibrator
    if (events = XPending(*(dpyb.get_display()))) { 
      //XEvent e;
      XNextEvent(*(dpyb.get_display()), e);
      printf("got event %d from number of events = %d\n", e->type, events);
	process_event(e);
	XFillRectangle(*(dpyb.get_display()), window->getTitleWindow(), gc,0,0,800,20);
	XFillRectangle(*(dpyb.get_display()), window->getWindow(), gc,0,0,800,600);
    	//XSync(*dpy, 0);
	}
	
  }
	XFlush(*(dpyb.get_display()));
}

int RayManta::process_event(XEvent *e) 
{

    printf("process eventtype= %d\n", e->type);
  switch (e->type) {
  case MapRequest:{
    printf("maprequest processed: %d windows\n", (int)windows.size());
    XMapWindow(e->xany.display, window->getTitleWindow()); 
    XMapWindow(e->xany.display,window->getWindow()); 
    break;
  }
/*  case UnmapNotify:{
    printf("unmapnotify");
    RayMantaWindow *win = (RayMantaWindow *) 0;
    if ((win = search_window(e->xunmap.window, True)))
      {
	if (window_type == CLIENT || window_type == TITLE)
	  {
	    erase_window(win); //because mapNotify reinserts the window =>
	    //It seems to me that unmapped windows don't get many events 
	    win->unmap(dpy);
	    printf("unmap succeeded.\n");
	  }
      }
    break;
  }*/
  case MotionNotify:{
    if (pressed)
      {
	XMotionEvent xm = e->xmotion;
	if (!motion)
	  {
	    x = xm.x; 
	    y = xm.y;
	    printf("x,y=%d, %d\n",xm.x,xm.y);
	  }
	dx = xm.x_root;
	dy = xm.y_root;
	window->move(&(e->xany.display), dx, dy);
	//printf("x,y= %d, %d\n", xm.x,xm.y);
	//do some rectanglodroiding here if not opaque move
	//FIXMEif (window_type == TITLE)
	  {
	    window->move(&(e->xany.display), dx-x, dy-y);
	    //XMoveWindow(*dpy, window->getWindow(), dx-x, dy-y);moved to move()
	    //XDrawRectangle(e->xany.display, root_window, gc, dx-x, dy-y, window->getWidth(), window->getHeight());//doesnt get erased yet
	  }
	motion = True;
      }
    printf("motion\n");
    break;
  }
  case ButtonPress:{
    RayMantaWindow *win = window;//(RayMantaWindow *) 0;
    //test if titlebar of a window got pressed
    //printf("e->window %d\n", (e->xbutton.window == None));
    //if (win = search_window(e->xbutton.window, True)) 
      //searches for the titlewindow
	XButtonEvent xb = e->xbutton;
    if (xb.y < 20) 
      {
	//if (window_type == CLIENT || window_type == TITLE)
	// {
	XRaiseWindow(e->xany.display, win->getWindow());
	XRaiseWindow(e->xany.display, win->getTitleWindow());
	pressed = True;
	//window = win;
	//}
//FIXME	if(window_type == LOWERBORDER)
	  {
	    init_x_root = xb.x_root;
	    init_y_root = xb.y_root;
	  }
      }
    printf("buttonpress\n");
    break;
  }
  case ButtonRelease:{
    if (pressed) {
      
    printf("type = %d\n", window_type);
      pressed = False;
      if (motion) {
	motion = False;
	//XRaiseWindow(dpy, window->getWindow());
	  window->move(dpyb.get_display(), dx-x, dy-y);
	/*switch (window_type){
	//case TITLE:{
	  window->move(dpy, dx-x, dy-y);
	  //XMoveWindow(dpy, window->getWindow(), dx-x, dy-y);
	  //break;
	}
	case LOWERBORDER:{
	  window->resize(init_x_root-dx, init_y_root-dy);
	  //XResizeWindow(dpy, window->getWindow(), 
	  //init_x_root,init_y_root);
	  break;
	}
	default:
	  break;
	}
      }
      else if (window_type == DESTROY)
	{
	  printf("destroying window now..\n");
	  erase_window(window);
	  XDestroySubwindows(display, window->getWindow());
	  XDestroyWindow(display, window->getWindow());
	}
    */} 
    }
    printf("buttonrelease\n");
    break;
  }
/*  case EnterNotify:{
    break;
  }    
  case LeaveNotify:
  case Expose:{//Very dangerous if a resize op gets interrupted by a expose
    RayMantaWindow *win = window;//(RayMantaWindow *) 0;
    //if(win = search_window(e->xexpose.window, False))  //False !!!!
      {
	//if (window_type == TITLE) //!!!!
	//{
	    win->expose(e->xexpose);
	    //positionWindow(win); happens in PxieWindow
	    //}
      }
    
    
    printf("expose\n");
    break;
  }
  case ConfigureRequest:{
    RayMantaWindow *win = (RayMantaWindow *) 0;
    if (win = search_window(e->xconfigurerequest.window, True))
      {
	//resize the parent & window !
	win->configure(dpy, e->xconfigurerequest);
	printf("existing window configure request\n");
      }
    else 
      {
	//XGrabServer(display); to grab or not to grab that's the question
	XConfigureRequestEvent xcre = e->xconfigurerequest;
	XWindowChanges xwc;
	xwc.x = xcre.x;
	xwc.y = xcre.y;
	xwc.width = xcre.width;
	xwc.height = xcre.height;
	xwc.border_width = xcre.border_width;
	xwc.sibling = xcre.above;
	xwc.stack_mode = xcre.detail;
	XConfigureWindow(e->xany.display, xcre.window, xcre.value_mask, &xwc);
	//XUngrabServer(e->xany.display);
	printf("Configure\n");
      }
    break;
  }
 *//* case DestroyNotify:{
    RayMantaWindow *win = (RayMantaWindow *) 0;
    if (win = search_window(e->xdestroywindow.window, True))
      {
	if(window_type == CLIENT || window_type == TITLE)
	  {
	    printf("Found window to destroy in list\n");
	    //erase_window(win);
	    win->destroy(dpy);
	    //erase_window(win); //maybe this should happen later
	  }
      }
    printf("destroyed\n");
    break;
  }*/
  default:
    break;
  }
  return 1;
}
/*
void RayManta::insert_window (RayMantaWindow *win)
{
  //--tullaris windows.insert_after(windows.previous(windows.end()), win);
  windows.push_back(win);//insert(windows.previous(windows.end()), win);
  printf("Window managed.\n");
}

RayMantaWindow * RayManta::search_window(Window win, bool set_window_type)
{
  //remove the set_window_type flag, which is a bad hack !
  std::list<RayMantaWindow *>::iterator first = windows.begin();
  std::list<RayMantaWindow *>::iterator last = windows.end();
  while (first != last)
    {
      printf("testing\n");
      std::list<RayMantaWindow *>::iterator next = first;
      ++next;
      if (((*first)->getTitleWindow() == win)) //add getWindow() for button destroys !
	//maybe split up the tests
	{
	  //break;
	  if(set_window_type)
	    {window_type = TITLE;}
	  printf("Found titlewindow in list\n");
	  return *first;
	}
      if (((*first)->getClientWindow() == win))
	{
	  if (set_window_type)
	    {
	      window_type = CLIENT;
	    }
	  printf("Found ClientWindow in list\n");
	  return *first;
	}
      if (((*first)->getLowerborderWindow() == win))
	{
	  if (set_window_type)
	    {
	      window_type = LOWERBORDER;
	    }
	  printf("Found lowerborderwindow in list\n");
	  return *first;
	}
      if (((*first)->getWindow() == win))
	{
	  if (set_window_type)
	    {
	      window_type = TOPLEVEL;
	    }
	  printf("Found lowerborderwindow in list\n");
	  return *first;
	}
 */     /*if (((*first)->getDestroyWindow() == win))
	{
	  //if (set_window_type)
	  // {
	      window_type = DESTROY;
	      //}
	  printf("Found destroywindow in list\n");
	  return *first;
	}
	*/
   /*   first= next;
    }
  printf("Window not found in list\n");
  return NULL;
  *//*
  for (;;) //do .. hwile
    {
      if (window_iterator.getTitleWindow() == window)
	{
	  break;
	  return window_iterator;
	}
      if (window_iterator == windows.end())
	{ 
	  return NULL; 
	  break;
	}
	}
  */
/*}

void RayManta::erase_window(RayMantaWindow * win)
{
  std::list<RayMantaWindow *>::iterator first = windows.begin();
  std::list<RayMantaWindow *>::iterator last = windows.end();
  while (first != last)
    {
      printf("testing\n");
      std::list<RayMantaWindow *>::iterator next = first;
      ++next;
      if ((*first) == win)
	//maybe split up the tests
	{
	  printf("Found window to be erased in list\n");
	  windows.erase(first);
	  return;
	}
      first= next;
    }
  printf("Window not found in list\n");
  return;
}
*/
void RayManta::positionWindow(Display **dpy, RayMantaWindow *win)
{
  //1. get free rects 
  //2. position in the smallest free rect that's big enough
  if (!windows.empty())
    {
      
      struct rect *free_rects[512]; //calculate size here instaed of 512
      //free_recxts sould be redundant if you check immediatly if the win fits
      //otherwise you position it in the smallest free rect that's big enough
      struct rect *window_rects[windows.size()]; //was struct rect* but bugged could be that sorting doesnt work right
      
      int display_width = DisplayWidth(*(dpyb.get_display()),screen);
      int display_height = DisplayHeight(*(dpyb.get_display()), screen);
      int win_x = win->getx();
      int win_y = win->gety();
      int win_width = win->getWidth();
      int win_height = win->getHeight();
      
      std::list<RayMantaWindow *>::iterator first = windows.begin();
      std::list<RayMantaWindow *>::iterator last = windows.end();
      for (int i = 0; first != last; i++)
	{
	  std::list<RayMantaWindow *>::iterator next = first;
	  ++next;
	  window_rects[i] = (struct rect *) malloc(sizeof(struct rect));
	  window_rects[i]->x = (*first)->getx();
	  window_rects[i]->y = (*first)->gety();
	  window_rects[i]->w = (*first)->getWidth();
	  window_rects[i]->h = (*first)->getHeight();
	  window_rects[i]->x_right = window_rects[i]->x + window_rects[i]->w;
	  window_rects[i]->y_right = window_rects[i]->y + window_rects[i]->h;
	  window_rects[i]->surface = (*first)->getWidth()*(*first)->getHeight();
	  first= next;
	  printf("x=%d of %p  ",(int)window_rects[i]->x, &(window_rects[i]->x));
	}
      //sort the windows so that they appear from left to right
      qsort(&window_rects, windows.size(), sizeof(struct rect *), &compare_x);//maybe need also a y sort
      
      //get free rects ..      
      printf("\nsorted:");
      int j = 0;      
      free_rects[j] = (struct rect *) malloc(sizeof(struct rect));
      for(int k = 0; k < windows.size(); k++)
	{
	  printf("x=%d ",window_rects[k]->x);
	  //..left of the window
	  if (window_rects[k]->x != 0)
	    {
	      for (int l = 0; l < k; l++)
		{
		  if ( k == 0) //leftmost window
		    {
		      free_rects[j]->x = 0;
		      free_rects[j]->y = 0;
		      free_rects[j]->w = window_rects[k]->x;
		      free_rects[j]->h = display_height;
		      free_rects[j]->x_right = window_rects[k]->x;
		      free_rects[j]->y_right = display_height;
		      j +=1;
		      free_rects[j] = (struct rect *) malloc(sizeof(struct rect));
		     
		    }
		  /*
		  else if (overlap()) 
		    {
		    ..
		      continue;
		    }
		  */
		  else  // not overlapping
		    {
		      int rightmost_x = 0;
		      //doesnt' take into account yet: windows who have their m->y_right between k->y k->y_right which would create 2 free rects
		      for (int m = 0; m < k; m++) //what about <= ?
			{//check if there's a window to the left
			  if (window_rects[m]->x_right > rightmost_x  && 
			      window_rects[m]->x_right < window_rects[k]->x &&
			      window_rects[m]->y_right > window_rects[k]->y)
			    {rightmost_x = window_rects[m]->x_right; }
			}
		      free_rects[j]->x = rightmost_x; 
		      free_rects[j]->w = window_rects[k]->x - rightmost_x;
		      free_rects[j]->x_right = free_rects[j]->x + free_rects[j]->w;
		      int lowest_y = 0;
		      for (int m = 0; m < k; m++)
			{//check if there is any window in between above
			  if (window_rects[m]->x_right > rightmost_x &&
			      window_rects[m]->y_right < window_rects[k]->y)
			    {
			      lowest_y = window_rects[m]->y_right;
			    }
			}
		      free_rects[j]->y = lowest_y;
		      int height = display_height;
		      for (int m = 0; m < k; m++)
			{//check if there is any window in between below 
			  if (window_rects[m]->x_right > rightmost_x &&
			      window_rects[m]->y > window_rects[k]->y_right &&
			      window_rects[m]->y < height)
			    {
			      height = window_rects[m]->y;
			    }
			}
		      free_rects[j]->h = height;
		      free_rects[j]->y_right = free_rects[j]->y + free_rects[j]->h;
		    }
		  
		  }
	    }
	  //..above the window 
	  //..under the window
	  //..right of the window
	}
      // insert win in the first (make it smallest) free rectangle
      for (int m = 0; m <= j; m++)
	{
	  printf("h = %d w = %d ", free_rects[m]->h, free_rects[m]->w);
	  if (free_rects[m]->h >= win_height && free_rects[m]->w >= win_width)
	    {
	      win->move(dpyb.get_display(), free_rects[m]->x, free_rects[m]->y);
	      return;
	    }
	}
      
    }
}
/*
  void RayManta::setBackground()
  {
  ImlibData *id;
  ImlibImage *im;
  Pixmap p,m;
  int w,h;
  id = Imlib_init(dpyb.get_display());
  im = Imlib_load_image(id, BACKGROUNDIMAGE);
  w = im->rgb_width; 
  h = im->rgb_height;
  Imlib_render(id, im, w, h);
  p = Imlib_move_image(id, im);
  m = Imlib_move_mask(id, im);
  XSetWindowBackgroundPixmap(dpyb.get_display(), getRootWindow(), p);
  if (m)
    {XShapeCombineMask(display, root_window, ShapeBounding, 0,0,m,ShapeSet);}
  XClearWindow(display, root_window);
  }
*/
/*
  void RayManta::foregroundWindows()
  {

  ImlibData *id;
  ImlibImage *im;
  Pixmap p,m;
  int w,h;
  id = Imlib_init(dpyb.get_display());
  im = Imlib_load_image(id, FOREGROUNDIMAGE);
  w = im->rgb_width; 
  h = im->rgb_height;
  Imlib_render(id, im, w, h);
  p = Imlib_move_image(id, im);
  m = Imlib_move_mask(id, im);
  XSetWindowAttributes attrib_create;
  unsigned long create_mask = CWBorderPixel | CWBackPixmap|
    CWEventMask|CWColormap;
  attrib_create.colormap = DefaultColormap(display, screen);
  attrib_create.background_pixmap = None;
  attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
    ButtonMotionMask |ExposureMask|EnterWindowMask | LeaveWindowMask;

  Window win = XCreateWindow(*(dpyb.get_display()), root_window, 
			     0, 
			     DisplayHeight(display,screen)-70, 
			     DisplayWidth(display,screen), 70, 0,
			     getDepth(), InputOutput, getVisual(),
			     create_mask, &attrib_create);
  
  XSetWindowBackgroundPixmap(*(dpyb.get_display()), win, p);
  XMapWindow(display, win);
  
  char * test = "Loading..";
  XmbDrawString(display, win, fontset, gc, 20, 20, test, strlen(test));

  Button *button = new Button (root_window, DisplayWidth(display,screen)-40,
			       DisplayHeight(display,screen)-40);
  button->setBackgroundPic("/usr/share/enlightenment/themes/ShinyMetal/pix/btn_exec_terminal_normal.png");

  //XDrawRectangle(display, win, gc, 2,2, 70,70);
  //XReparentWindow(*(dpyb.get_display()), win, root_window, 0, 0);
  //if (m)
  //  {XShapeCombineMask(display, root_window, ShapeBounding, 0,0,m,ShapeSet);}
  //XClearWindow(display, win);
  //XClearWindow(display, root_window);
}
*/

Pixel RayManta::GetColor(Display **dpy, char *name)
{
  XColor color;
  XWindowAttributes attributes;

  XGetWindowAttributes(*(dpyb.get_display()),getRootWindow(),&attributes);
  color.pixel = 0;
   if (!XParseColor (*(dpyb.get_display()), attributes.colormap, name, &color)) 
     {
       printf("parse no color");
     }
   else if(!XAllocColor (*(dpyb.get_display()), attributes.colormap, &color)) 
     {
       printf("parse no color");
     }
  return color.pixel;
}

int compare_x(const void * a, const void * b)
{
  printf("compare_x a.x %d ",*((int *)((struct rect *)a)->x));
  
  if (*((int *)((struct rect *)a)->x) < *((int *)((struct rect *)b)->x))
    {return -1;}
  else if (*((int *)((struct rect *)a)->x) > *((int *)((struct rect *)b)->x))
    {return 1;}
  else
    {return 0;}
  
}

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaEngine.h"

namespace ray3d {

}
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaGA.h"
#include <cstdlib>
#include <iostream>

double RayMantaGA::fitness()
{

	double fitn;


	for (Genes::iterator gi = genes.begin(); gi != genes.end(); gi++) {

		fitn += (*gi);

	}

	fitn /= genes.size();

	return fitn;
}

double RayMantaGA::fitness2()
{

	double fitn;

	for (Genes::iterator gi = genes.begin(); gi != genes.end(); gi++) {

		fitn += (*gi);

	}

	fitn * fitn * std::cos(std::sqrt(2)/2);

	return fitn;
}

double RayMantaGA::fitness3()
{
	Genes learningrates;
	for (int j = 0; j < genes.size(); j++)
		learningrates[j] = ::random();

	double fitn;
	int i = 0;
	for (Genes::iterator gi = genes.begin(); gi != genes.end(); gi++, i++) {
		fitn += (*gi)*learningrates[i];

	}

	fitn /= genes.size();

	return fitn;
}

double RayMantaGA::fitness4()
{
	Genes learningrates;
	for (int j = 0; j < genes.size(); j++)
		learningrates[j] = ::random();

	double fitn;
	int i = 0;
	for (Genes::iterator gi = genes.begin(); gi != genes.end(); gi++, i++) {
		if ((*gi) > learningrates[i])
			fitn += (*gi);

	}

	fitn /= genes.size();

	return fitn;
}



Genes RayMantaGA::mutate(int index)
{

	if (genes[index] == 0) genes[index] = 1; else genes[index] = 0;
	return genes;	
}

Genes RayMantaGA::crossover(int index1, int index2, Genes g)
{
	crossovergenes = g;
	//crossover from index1 to index2
	for (int i = index1; i < index2; i++) {
		genes[i] = g[i];
	}

}

Genes RayMantaGA::crossover2(int index1, int index2, Genes g)
{
	crossovergenes = g;
	//crossover from index1 to index2
	for (int i = index1; i < index2; i++) {
		genes[i] = g[i]*genes[i];
	}

}

Genes RayMantaGA::crossoversame(int index1, int index2)
{
	//from index1 to index2
	for (int i = index1; i < index2; i++) {
		genes[i] *= crossovergenes[i];
	}

}

Genes RayMantaGA::crossoversame2(int index1, int index2)
{
	//from index1 to index2
	for (int i = index1; i < index2; i++) {
		genes[i] = genes[i]*genes[i];
	}

}

int RayMantaGA::eventloop(int ngenes)
{
//	init(ngenes);

//	for (;;) {
		long int r = ::random();
		int index = r % ngenes;

		mutate(index);
	
		std::cout<<"fitness"<<fitness()<<std::endl;

//	}

	return 0;
}
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaImageBase.h"
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaImage.h"
#include "RayManta.h"

RayMantaImage::RayMantaImage (Display **dpy) 
{
//	init();
  
	int depth = DefaultDepth(*dpy, DefaultScreen(*dpy));
  	Visual *visual = DefaultVisual(*dpy, DefaultScreen(*dpy));
//	image = XCreateImage(*dpy, visual, depth, XYPixmap,0,(char *)post_xpm,24,24,8,1); 
}

int RayMantaImage::draw(Display **dpy, Window *w, int destxx, int destyy)
{
#define NIL (0)
  GC gc = XCreateGC(*dpy, *w, 0, NIL);
  XPutImage(*dpy, *w, gc, image, 0,0,destxx,destyy,500,500);

	return 0;
}

int RayMantaImage::putpixel(int xx, int yy, unsigned long value)
{
	XPutPixel(image, xx,yy,value);

}


/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaMatrix3.h"
#include <iostream>

namespace ray3d {
	
double Vector3::operator*(Vector3 const& v)
{

	return (const_cast<Vector3&>(v).get_x()*get_x() + const_cast<Vector3&>(v).get_y()*get_y()+const_cast<Vector3&>(v).get_z()*get_z());

}

Matrix3::Matrix3(Vector3 const& row1, Vector3 const& row2, Vector3 const& row3)
{
	x11 = const_cast<Vector3&>(row1).get_x();
	x12 = const_cast<Vector3&>(row1).get_y();
	x13 = const_cast<Vector3&>(row1).get_z();
	x21 = const_cast<Vector3&>(row2).get_x();
	x22 = const_cast<Vector3&>(row2).get_y();
	x23 = const_cast<Vector3&>(row2).get_z();
	x31 = const_cast<Vector3&>(row3).get_x();
	x32 = const_cast<Vector3&>(row3).get_y();
	x33 = const_cast<Vector3&>(row3).get_z();
}

Matrix3 Matrix3::operator*(Matrix3 const& m)
{
//	if (m == *this)
//		return *this;
	//compiler optimized	
	return Matrix3(const_cast<Matrix3&>(m).get_x11()*get_x11()+
			const_cast<Matrix3&>(m).get_x12()*get_x21()+
			const_cast<Matrix3&>(m).get_x13()*get_x31(),
			const_cast<Matrix3&>(m).get_x11()*get_x21()+
			const_cast<Matrix3&>(m).get_x12()*get_x22()+
			const_cast<Matrix3&>(m).get_x13()*get_x23(),
			const_cast<Matrix3&>(m).get_x11()*get_x31()+
			const_cast<Matrix3&>(m).get_x12()*get_x32()+
			const_cast<Matrix3&>(m).get_x13()*get_x33(),
			const_cast<Matrix3&>(m).get_x21()*get_x11()+
			const_cast<Matrix3&>(m).get_x22()*get_x21()+
			const_cast<Matrix3&>(m).get_x23()*get_x31(),
			const_cast<Matrix3&>(m).get_x21()*get_x21()+
			const_cast<Matrix3&>(m).get_x22()*get_x22()+
			const_cast<Matrix3&>(m).get_x23()*get_x23(),
			const_cast<Matrix3&>(m).get_x21()*get_x31()+
			const_cast<Matrix3&>(m).get_x22()*get_x32()+
			const_cast<Matrix3&>(m).get_x23()*get_x33(),
			const_cast<Matrix3&>(m).get_x31()*get_x11()+
			const_cast<Matrix3&>(m).get_x32()*get_x21()+
			const_cast<Matrix3&>(m).get_x33()*get_x31(),
			const_cast<Matrix3&>(m).get_x31()*get_x21()+
			const_cast<Matrix3&>(m).get_x32()*get_x22()+
			const_cast<Matrix3&>(m).get_x33()*get_x23(),
			const_cast<Matrix3&>(m).get_x31()*get_x31()+
			const_cast<Matrix3&>(m).get_x32()*get_x32()+
			const_cast<Matrix3&>(m).get_x33()*get_x33());
}

Vector3 Matrix3::operator*(Vector3 const& v)
{
	return Vector3(get_x11()*const_cast<Vector3&>(v).get_x()+
			get_x12()*const_cast<Vector3&>(v).get_y()+
			get_x13()*const_cast<Vector3&>(v).get_z(),
			get_x21()*const_cast<Vector3&>(v).get_x()+
			get_x22()*const_cast<Vector3&>(v).get_y()+
			get_x23()*const_cast<Vector3&>(v).get_z(),
			get_x31()*const_cast<Vector3&>(v).get_x()+
			get_x32()*const_cast<Vector3&>(v).get_y()+
			get_x33()*const_cast<Vector3&>(v).get_z());

}
} //namespace ray3d
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaMatrix4.h"
#include <iostream>

namespace ray3d {
	
double Vector4::operator*(Vector4 const& v)
{

	return (const_cast<Vector4&>(v).get_x()*get_x() + const_cast<Vector4&>(v).get_y()*get_y()+const_cast<Vector4&>(v).get_z()*get_z()+const_cast<Vector4&>(v).get_t());

}

Matrix4::Matrix4(Vector4 const& row1, Vector4 const& row2, Vector4 const& row3, Vector4 const& row4)
{
	x11 = const_cast<Vector4&>(row1).get_x();
	x12 = const_cast<Vector4&>(row1).get_y();
	x13 = const_cast<Vector4&>(row1).get_z();
	x14 = const_cast<Vector4&>(row1).get_t();
	x21 = const_cast<Vector4&>(row2).get_x();
	x22 = const_cast<Vector4&>(row2).get_y();
	x23 = const_cast<Vector4&>(row2).get_z();
	x24 = const_cast<Vector4&>(row2).get_t();
	x31 = const_cast<Vector4&>(row3).get_x();
	x32 = const_cast<Vector4&>(row3).get_y();
	x33 = const_cast<Vector4&>(row3).get_z();
	x34 = const_cast<Vector4&>(row3).get_t();
	x41 = const_cast<Vector4&>(row4).get_x();
	x42 = const_cast<Vector4&>(row4).get_y();
	x43 = const_cast<Vector4&>(row4).get_z();
	x44 = const_cast<Vector4&>(row4).get_t();
}

Matrix4 Matrix4::operator*(Matrix4 const& m)
{
//	if (m == *this)
//		return *this;
	
	return Matrix4(const_cast<Matrix4&>(m).get_x11()*get_x11()+
			const_cast<Matrix4&>(m).get_x12()*get_x21()+
			const_cast<Matrix4&>(m).get_x13()*get_x31()+
			const_cast<Matrix4&>(m).get_x14()*get_x41(),
			const_cast<Matrix4&>(m).get_x11()*get_x21()+
			const_cast<Matrix4&>(m).get_x12()*get_x22()+
			const_cast<Matrix4&>(m).get_x13()*get_x23()+
			const_cast<Matrix4&>(m).get_x14()*get_x24(),
			const_cast<Matrix4&>(m).get_x11()*get_x31()+
			const_cast<Matrix4&>(m).get_x12()*get_x32()+
			const_cast<Matrix4&>(m).get_x13()*get_x33()+
			const_cast<Matrix4&>(m).get_x14()*get_x34(),
			const_cast<Matrix4&>(m).get_x11()*get_x41()+
			const_cast<Matrix4&>(m).get_x12()*get_x42()+
			const_cast<Matrix4&>(m).get_x13()*get_x43()+
			const_cast<Matrix4&>(m).get_x14()*get_x44(),
			const_cast<Matrix4&>(m).get_x21()*get_x11()+
			const_cast<Matrix4&>(m).get_x22()*get_x21()+
			const_cast<Matrix4&>(m).get_x23()*get_x31()+
			const_cast<Matrix4&>(m).get_x24()*get_x41(),
			const_cast<Matrix4&>(m).get_x21()*get_x21()+
			const_cast<Matrix4&>(m).get_x22()*get_x22()+
			const_cast<Matrix4&>(m).get_x23()*get_x23()+
			const_cast<Matrix4&>(m).get_x24()*get_x24(),
			const_cast<Matrix4&>(m).get_x21()*get_x31()+
			const_cast<Matrix4&>(m).get_x22()*get_x32()+
			const_cast<Matrix4&>(m).get_x23()*get_x33()+
			const_cast<Matrix4&>(m).get_x24()*get_x34(),
			const_cast<Matrix4&>(m).get_x21()*get_x41()+
			const_cast<Matrix4&>(m).get_x22()*get_x42()+
			const_cast<Matrix4&>(m).get_x23()*get_x43()+
			const_cast<Matrix4&>(m).get_x24()*get_x44(),
			const_cast<Matrix4&>(m).get_x31()*get_x11()+
			const_cast<Matrix4&>(m).get_x32()*get_x21()+
			const_cast<Matrix4&>(m).get_x33()*get_x31()+
			const_cast<Matrix4&>(m).get_x34()*get_x41(),
			const_cast<Matrix4&>(m).get_x31()*get_x21()+
			const_cast<Matrix4&>(m).get_x32()*get_x22()+
			const_cast<Matrix4&>(m).get_x33()*get_x23()+
			const_cast<Matrix4&>(m).get_x34()*get_x24(),
			const_cast<Matrix4&>(m).get_x31()*get_x31()+
			const_cast<Matrix4&>(m).get_x32()*get_x32()+
			const_cast<Matrix4&>(m).get_x33()*get_x33()+
			const_cast<Matrix4&>(m).get_x34()*get_x34(),
			const_cast<Matrix4&>(m).get_x31()*get_x41()+
			const_cast<Matrix4&>(m).get_x32()*get_x42()+
			const_cast<Matrix4&>(m).get_x33()*get_x43()+
			const_cast<Matrix4&>(m).get_x34()*get_x44(),
			
			const_cast<Matrix4&>(m).get_x41()*get_x11()+
			const_cast<Matrix4&>(m).get_x42()*get_x21()+
			const_cast<Matrix4&>(m).get_x43()*get_x31()+
			const_cast<Matrix4&>(m).get_x44()*get_x41(),
			const_cast<Matrix4&>(m).get_x41()*get_x21()+
			const_cast<Matrix4&>(m).get_x42()*get_x22()+
			const_cast<Matrix4&>(m).get_x43()*get_x23()+
			const_cast<Matrix4&>(m).get_x44()*get_x24(),
			const_cast<Matrix4&>(m).get_x41()*get_x31()+
			const_cast<Matrix4&>(m).get_x42()*get_x32()+
			const_cast<Matrix4&>(m).get_x43()*get_x33()+
			const_cast<Matrix4&>(m).get_x44()*get_x34(),
			const_cast<Matrix4&>(m).get_x41()*get_x41()+
			const_cast<Matrix4&>(m).get_x42()*get_x42()+
			const_cast<Matrix4&>(m).get_x43()*get_x43()+
			const_cast<Matrix4&>(m).get_x44()*get_x44()
					
	);
}

Vector4 Matrix4::operator*(Vector4 const& v)
{

	return Vector4(get_x11()*const_cast<Vector4&>(v).get_x()+
			get_x12()*const_cast<Vector4&>(v).get_y()+
			get_x13()*const_cast<Vector4&>(v).get_z()+
			get_x14()*const_cast<Vector4&>(v).get_t(),
			get_x21()*const_cast<Vector4&>(v).get_x()+
			get_x22()*const_cast<Vector4&>(v).get_y()+
			get_x23()*const_cast<Vector4&>(v).get_z()+
			get_x24()*const_cast<Vector4&>(v).get_t(),
			get_x31()*const_cast<Vector4&>(v).get_x()+
			get_x32()*const_cast<Vector4&>(v).get_y()+
			get_x33()*const_cast<Vector4&>(v).get_z()+
			get_x34()*const_cast<Vector4&>(v).get_t(),
			get_x41()*const_cast<Vector4&>(v).get_x()+
			get_x42()*const_cast<Vector4&>(v).get_y()+
			get_x43()*const_cast<Vector4&>(v).get_z()+
			get_x44()*const_cast<Vector4&>(v).get_t());

}
} //namespace ray3d
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaMatrix.h"

//no test for equal rows/columns	
double Vector::operator*(Vector const& v)
{
	double result = 0;

	for (PointsVector::iterator vi = const_cast<Vector&>(v).get_points().begin(), pi = points.begin(); pi != points.end(); pi++, vi++)
		result += (*pi)*(*vi);

	return result;

}

//no test for equal rows/columns	
Matrix Matrix::operator*(Matrix const& m)
{
//	if (m == *this)
//		return *this;

	PointsMatrix pms;
	PointsVector pvs;	

	for (PointsMatrix::iterator pi = const_cast<Matrix&>(m).get_points().begin(), qi = points.begin(); qi != points.end(); pi++, qi++)
		for (PointsVector::iterator vi = const_cast<PointsVector&>(*pi).begin(), wi = const_cast<PointsVector&>(*qi).begin(); vi != const_cast<PointsVector&>(*pi).end(); wi++, vi++)
			//FIXME transpose
			pvs.push_back((*vi)*(*wi));
		pms.push_back(pvs);
		pvs = PointsVector();	

	return Matrix(pms);
}

Vector Matrix::operator*(Vector const& v)
{
	PointsVector pvs;	

	for (PointsMatrix::iterator pi = get_points().begin(); pi != points.end(); pi++)
		pvs.push_back(const_cast<Vector&>(v) * (*pi));

	return Vector(pvs);	
}

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaModel.h"
#include<cstdlib>

namespace ray3d {	

#define VECTORSIZE (3)

int Model::filein(std::string const& filename)
{
	std::ifstream *ifs = new std::ifstream(filename.c_str());
	char *buf = new char[1024];//FIXME fiexed size
	char *buf2 = new char[1024];//FIXME fiexed size
	char *buf3 = new char[1024];//FIXME fiexed size
	char *buf4 = new char[1024];//FIXME fiexed size
	for (; !ifs->eof(); ) {
			(*ifs) >> buf;
			if (ifs->eof()) break;
			(*ifs) >> buf2;
			if (ifs->eof()) break;
			(*ifs) >> buf3;
			if (ifs->eof()) break;
			(*ifs) >> buf4;
			_points.push_back(Point(std::atof(buf),std::atof(buf2),std::atof(buf3),std::atof(buf4)));
	}

	return 0;
}

int Model::fileout(std::string const& filename)
{
	char buf[1024];
	std::ofstream *ofs = new std::ofstream(filename.c_str());
	for (int i = 0; i < _points.size(); i++) {
		sprintf(buf, "%e ", (double)(_points[i][0]));
		(*ofs) << buf; 
		sprintf(buf, "%e ", (double)(_points[i][1]));
		(*ofs) << buf; 
		sprintf(buf, "%e ", (double)(_points[i][2]));
		(*ofs) << buf; 
		sprintf(buf, "%e ", (double)(_points[i][3]));
		(*ofs) << buf; 
	}	
	return 0;
}

int Model::draw(Display **dpy1, Window *w)
{

	#define NIL (0)

	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++ ) {
      		GC gc = XCreateGC(*dpy1, *w, 0, NIL);
		XDrawLine(*dpy1, *w, gc, (*vi).get_x(),(*vi).get_y(),(*vi).get_x(),(*vi).get_y());

	}
	return 0;
}


int Model::rotatex(Engine const& engine, double t)
{
	Matrix3 rotm(const_cast<Engine&>(engine).rotatex(t));
	std::vector <Point> retv;
	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++ ) {

		retv.push_back(Point(rotm*static_cast<Vector3&>(*vi)));

	}
	_points = *&retv;
	return 0;
}
int Model::rotatey(Engine const& engine, double t)
{
	Matrix3 rotm(const_cast<Engine&>(engine).rotatey(t));
	std::vector <Point> retv;
	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++ ) {

		retv.push_back(Point(rotm*static_cast<Vector3&>(*vi)));

	}
	_points = *&retv;
	return 0;
}
int Model::rotatez(Engine const& engine, double t)
{
	Matrix3 rotm(const_cast<Engine&>(engine).rotatez(t));
	std::vector <Point> retv;
	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++ ) {

		retv.push_back(Point(rotm*static_cast<Vector3&>(*vi)));

	}
	_points = *&retv;
	return 0;
}
int Model::rotate(Engine const& engine, double t1, double t2, double t3)
{
	Matrix3 rotm(const_cast<Engine&>(engine).rotate(t1,t2,t3));
	std::vector <Point> retv;
	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++ ) {

		retv.push_back(Point(rotm*static_cast<Vector3&>(*vi)));

	}
	_points = *&retv;
	return 0;
}
/*
int Model::raytrace(Display **dpy, Window *w)
{
}

int Model::dithersunray(Display **dpy, Window *w)
{
}

*/
} // namespace ray3d

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional> 
#include <unistd.h> 
#include <signal.h> 
#include <cstdlib> 
#include "RayMantaNet.h"

inline void signalforkfunc(int) {

	//auto unpause
}

template <class S, class T>
int RayMantaNet<S,T>::markovpropagate() 
{
	/*
	* FIXME NOTE :
	* You have to propagate the processes for running
	* Use the RayMantaMatrix classes for matrix propagation
	*/


	for (std::map<int, pid_t>::iterator vi = _scheduler.begin();
		vi != _scheduler.end(); vi++) {

		(*vi);	

	} 
	return 0;
}

template <class S, class T>
int RayMantaNet<S,T>::waitforall() 
{

	killpg(_pgid, 30); //SIGUSR1
	return 0;
}

template <class S, class T>
int RayMantaNet<S,T>::fork()
{
	pid_t pid, pid2 = -1;
	if ((pid = ::fork()) < 0)
		return -1;
	else if (pid2 == 0) { //child
		if ((pid = ::fork()) < 0)
			return -1;
		else if (pid == 0) { //child
			setpgid(pid, _pgid);
			_scheduler[_scheduler.size()] = pid;//FIXME -1 


			markovpropagate();
	
			signal(30,signalforkfunc);

			//pause process 
			//if (pid != _scheduler[0])
			//	pause();
		} else { /* parent 2 */ }
		std::exit(0);
	} else { //parent
		std::exit(0);
	}

	return 0;
}

template <class S,class T>
int RayMantaNet<S,T>::fork(S const& loadfilename, S const& parsefilename, int const& wordid)
{

	pid_t pid, pid2 = -1;
	if ((pid = ::fork()) < 0)
		return -1;
	else if (pid2 == 0) { //child
		if ((pid = ::fork()) < 0)
			return -1;
		else if (pid == 0) { //child
			setpgid(pid, _pgid);
			_scheduler[_scheduler.size()] = pid;//FIXME -1 	
			signal(30,signalforkfunc);

			//wait for root window to be initialized
			if (pid != _scheduler[0])
				pause();
		} else { /* parent 2 */ }
		std::exit(0);
	} else { //parent
		std::exit(0);
	}

	return 0;
}
template class RayMantaNet<std::string, void *>;
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional> 
#include <unistd.h> 
#include <signal.h> 
#include <cstdlib> 
#include "RayMantaNetMarkov2.h"
#include "Boltzman.h"

inline void signalforkfunc(int) {

	//auto unpause
}

template <class S, class T>
int RayMantaNetMarkov2<S,T>::markovpropagate(Matrix const& m) 
{
	/*
	* FIXME NOTE :
	* You have to propagate the processes for running
	* Use the RayMantaMatrix classes for matrix propagation
	*/

	std::cout<<"Entering critical section..."<<std::endl;
	int mindex = 0, mindex2 = 0;
	for (std::map<int, pid_t>::iterator vi = static_cast<std::map<int, pid_t> >(_scheduler).begin(); vi != static_cast<std::map<int, pid_t> >(_scheduler).end(); vi++, mindex++) {
		
		for (mindex2 = 0; mindex2 < ((const_cast<Matrix&>(m).get_points())[mindex])[mindex2]; mindex2++) { 
			double d = const_cast<Matrix&>(m).get_points()[mindex][mindex2];
			markovtest(d, (*vi).second);
		}
	} 

/*
	for (std::map<int, pid_t>::iterator vi = _scheduler.begin();
		vi != _scheduler.end(); vi++) {

		(*vi);	

	} 
*/	return 0;
}

template <class S, class T>
int RayMantaNetMarkov2<S,T>::waitforall() 
{

	killpg(_pgid, 30); //SIGUSR1
	return 0;
}

template <class S, class T>
int RayMantaNetMarkov2<S,T>::fork()
{
	pid_t pid, pid2 = -1;
	if ((pid = ::fork()) < 0)
		return -1;
	else if (pid2 == 0) { //child
		if ((pid = ::fork()) < 0)
			return -1;
		else if (pid == 0) { //child
			setpgid(pid, _pgid);
			_scheduler[_scheduler.size()] = pid;//FIXME -1 

			Boltzman b(10,10);
			Matrix m = b.generateboltzmanmatrix(b,10,10); //FIXME1 fill in matrix points
			markovpropagate(m);
	
			signal(30,signalforkfunc);

			//pause process 
			//if (pid != _scheduler[0])
			//	pause();
		} else { /* parent 2 */ }
		std::exit(0);
	} else { //parent
		std::exit(0);
	}

	return 0;
}

template<class S, class T>	
int RayMantaNetMarkov2<S,T>::markovtest(double d, pid_t pid)
{

	/*
	* You have to measure here for managing the Drawing process
	* i.e. from fork networks
	*/

	/*empty*/
} 

template class RayMantaNetMarkov2<std::string, void *>;
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional> 
#include <cstdlib> 
#include "RayMantaMatrix.h"
#include "RayMantaNetMarkov.h"
#include <map>

template<class S, class T>	
Matrix RayMantaNetMarkov<S,T>::generateboltzmanmatrix(Boltzman const& b, int cols, int rows)
{

	Matrix m;
	Energies egs;

	for (int k = 0; k < rows*cols; k++)
		egs.push_back(std::rand());


	for (int i = 0; i < rows; i++){
		Vector v;
	for (int j = 0; j < cols; j++){
		
		v.add(const_cast<Boltzman&>(b).f2(rows*cols,egs,0.5,10));
	}
		m.add(v.get_points());
	}

	return m;

}

template<class S, class T>	
int RayMantaNetMarkov<S,T>::markovpropagate(Matrix const& m) 
{
	/*
	* FIXME NOTE :
	* You have to propagate the processes for running
	* Use the RayMantaMatrix classes for matrix propagation
	*/
	std::cout<<"Entering critical section..."<<std::endl;
	int mindex = 0, mindex2 = 0;
	for (std::map<int, pid_t>::iterator vi = static_cast<std::map<int, pid_t> >(_scheduler).begin(); vi != static_cast<std::map<int, pid_t> >(_scheduler).end(); vi++, mindex++) {
		
		for (mindex2 = 0; mindex2 < ((const_cast<Matrix&>(m).get_points())[mindex])[mindex2]; mindex2++) { 
			double d = const_cast<Matrix&>(m).get_points()[mindex][mindex2];
			markovtest(d, (*vi).second);
		}
	} 
	return 0;
}

template<class S, class T>	
int RayMantaNetMarkov<S,T>::markovtest(double d, pid_t pid)
{

	/*
	* You have to measure here for managing the Drawing process
	* i.e. from fork networks
	*/

	/*empty*/
} 

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <pthread.h> 
#include <cstdlib> 
#include "RayMantaNetPthread.h"

void *forkfunc(void *arg)
{
	return NULL;

}

template <class S, class T>
int RayMantaNetPthread<S,T>::waitforall() 
{

	return 0;

}

template <class S, class T>
int RayMantaNetPthread<S,T>::fork(S const& loadfilename, S const& parsefilename, int const& wordid)
{
	pthread_t pid;
	//	void *arg = new Parser<S,T>(loadfilename, parsefilename,wordid); //NOTE : use & Parser for warning;
	pthread_create(&pid,NULL,&forkfunc,NULL);
	if (pid < 0)
		return -1;
 	_scheduler[(int)_scheduler.size()] = pid;	
	return 0;
}
/*
template <class S, class T>
int RayMantaNetPthread<S,T>::parse(Parser<S,T> parser)
{

	return parser.parse();

}
*/


template class RayMantaNetPthread<std::string, void * >;

#include "RayMantaPixmapImage.h"
#include "RayManta.h"

RayMantaPixmapImage::RayMantaPixmapImage (Display **dpy, std::string const& filename)
{

  XpmAttributes attributes;
  attributes.valuemask = XpmReturnPixels | XpmReturnExtensions | XpmExactColors
    | XpmCloseness;
  attributes.exactColors = False;
  attributes.closeness = 40000;
  int ret;
  if((ret = XpmReadFileToImage(*dpy,
			 const_cast<char *>(const_cast<std::string&>(filename).c_str()),
			 &image,
			 &shape,
			 &attributes)) != 0)
    {
      printf("RayMantaPixmapImage's XpmReadPixmap from file : error %d\n", ret);
      delete this;
      return;
    }

}

RayMantaPixmapImage::~RayMantaPixmapImage ()
{
}

int RayMantaPixmapImage::draw(Display **dpy, Window *w, int destxx, int destyy)
{
#define NIL (0)
  GC gc = XCreateGC(*dpy, *w, 0, NIL);
  XPutImage(*dpy, *w, gc, image, 0,0,destxx,destyy,500,500);
}

int RayMantaPixmapImage::putpixel(int xx, int yy, unsigned long value)
{
	XPutPixel(image, xx,yy,value);

}

unsigned long RayMantaPixmapImage::getpixel(int xx, int yy)
{
	return XGetPixel(image, xx,yy);

}

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaPixmapTextureModel.h"
#include "RayMantaMatrix3.h"
#include<cstdlib>

namespace ray3d {

/*
* NOTE : You map the _xpmimage 
* (xpm XImage, see file RayMantaPixmapImage.h/.cc)
* onto the walls, curved,dungeon tower and straight walls.
*/	
//main draw method

int PixmapTexture::initdraw(PixmapTextureModel& model)
{
	thetax = 1.5;
	thetay = 2.5;
	thetaz = 3.5;

	initdraw1(model);//,/*offsetx+*/100,/*offsety+*/100);

}

int PixmapTexture::drawmain(Display **dpy, Window *w, int offsetx, int offsety)
{
	//drawcurved3(dpy,w,offsetx,offsety);
	//drawsmallandrotate(dpy,w,offsetx+200,offsety+200);
	//drawenlargeandrotate2(dpy,w,offsetx+100,offsety+100);
	drawbiggerandrotate(dpy,w,offsetx+100,offsety+100);
	//drawsmaller(dpy,w,offsetx+200,offsety+200,1,1);
	//draw3(dpy,w);
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double fracx = _w/_enlargew, fracy = _h/_enlargeh;
	int prevx = 0, prevy = 0;
	
	for (int yy = 0; yy < _enlargeh; yy++) {
		for (int xx = 0; xx < _enlargew; xx++) { 
			//_alpha += 5;//0.9;
			_alpha = 5;//0.9;
			_beta = 5;
			Point pt(xx*fracx,yy*fracy,1);
	
					
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
			values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        		gc = XCreateGC(*dpy, *w, valuemask, &values);
			XDrawLine(*dpy, *w, gc,
				offsetx+(int)pt.get_x(),
				offsety+(int)pt.get_y(),
				offsetx+(int)pt.get_x(),
				offsety+(int)pt.get_y());
			for (int k = prevy/_beta; k < pt.get_y(); k++)  {
				for (int j = prevx/_alpha; j < pt.get_x(); j++)  {
				XDrawLine(*dpy, *w, gc,
					offsetx+(int)prevx/_alpha+j,
					offsety+(int)prevy/_beta+k,
					offsetx+(int)prevx/_alpha+j,
					offsety+(int)prevy/_beta+k);
			}
			}
			prevx = xx;//pt.get_x();//xx
			prevy = yy;//pt.get_y();
			}
			}
	return 0;
}
//draw smaller version with curved sides (e.g. dungeon tower)
int PixmapTexture::drawcurved(Display **dpy, Window *w, int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	double fracx = _w/_enlargew, fracy = _h/_enlargeh;
	for (int xx = 0; xx < _w; xx++) { 
		for (int yy = 0; yy < _h; yy++) {
				//Point p1((*vi)[i-1]);
				//Point p2((*vi)[i]);
				//Point p1(_polygons[0][0].get_x(),_polygons[0][0].get_y(),1);
				Point pt(xx*fracx,yy*fracy,1);
				Point p2(xx,yy,1);
				//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
				//pt = pt.scaley(angle);//_pixmaptexture.get_alpha());
				//_globalalpha +=  _alpha;
				//_alpha += 5;//0.9;
				//Point pt(((int)((xx*_alpha/_enlargew))),((int)((yy*_alpha/_enlargeh))),1);
			//	//_global += 1;
	
					
				//unsigned long color = 65000;
				unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				//if (_globalalpha > 1) {
				for (int j = prevx; j < xx*_alpha/_enlargew; j++) {
				for (int k = prevy; k < yy*_alpha/_enlargeh; k++) {
					Point pt2((int)((xx+j)*_alpha/_enlargew),(int)((yy)*_alpha/_enlargeh),1);
					XDrawLine(*dpy, *w, gc,offsetx+(int)pt2.get_x(),offsety+(int)pt2.get_y(),offsetx+(int)pt2.get_x(),offsety+(int)pt2.get_y());
					Point pt3((int)((xx)*_alpha/_enlargew),(int)((yy+k)*_alpha/_enlargeh),1);
					XDrawLine(*dpy, *w, gc,offsetx+(int)pt3.get_x(),offsety+(int)pt3.get_y(),offsetx+(int)pt3.get_x(),offsety+(int)pt3.get_y());
				}
				}
				//	_global = 0;
				//	_globalalpha = 0;
				//}
				prevy = yy*_alpha/_enlargeh;
				prevx = xx*_alpha/_enlargew;
			}
			}
			//}
//		}
		
	return 0;
}
int PixmapTexture::draw3(Display **dpy, Window *w)
{
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

	const std::string filename("./post.xpm");
	//NOTE: do not draw polygon lines, rather texture in between 
	//NOTE: polygons are fixed at 4 points
//	ray3d::Polygon poly;
/*	poly += ray3d::Point(20,20,20);
	poly += ray3d::Point(102,102,102);
	poly += ray3d::Point(120,120,120);
	poly += ray3d::Point(20,20,20);
	_polygons.push_back(poly);
*/	double prevxx = 0, prevyy = 0;
	//for (PolygonVector::iterator vi = _polygons.begin(); vi != _polygons.end(); vi++ ) {
			//for (int i = 0; i < 4; i++) {
			for (int xx = 0; xx < get_w(); xx++) { 
			for (int yy = 0; yy < get_h(); yy++) {
				//Point p1((*vi)[i-1]);
				//Point p2((*vi)[i]);
				//Point p1(_polygons[0][0].get_x(),_polygons[0][0].get_y(),1);
				Point p2(xx,yy,1);
				//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
				//pt = pt.scaley(angle);//_pixmaptexture.get_alpha());
				_alpha -= 0.001;
				//_alpha += 0.001;
				Point pt(((int)(xx*(_alpha))%24),((int)(yy*(_alpha))%24),1);
				int j = 0;
				for (j = 0; j < prevxx; j++) {
					if (pt.get_x()-prevxx > 1) {
        				gc = XCreateGC(*dpy, *w, valuemask, &values);
					XDrawLine(*dpy, *w, gc,200+(int)pt.get_x()+j,200+(int)pt.get_y(),200+(int)pt.get_x()+j,200+(int)pt.get_y());
					} else { break; }
				}
				XDrawLine(*dpy, *w, gc,100+(int)pt.get_x()+j,100+(int)pt.get_y(),100+(int)pt.get_x()+j,100+(int)pt.get_y());
				//unsigned long color = 65000;
				unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				/////XDrawLine(*dpy, *w, gc, p1.get_x()+(int)pt.get_x(),p1.get_y()+(int)pt.get_y(),p1.get_x()+(int)pt.get_x(),p1.get_y()+(int)pt.get_y());
				XDrawLine(*dpy, *w, gc,100+(int)pt.get_x(),100+(int)pt.get_y(),100+(int)pt.get_x(),100+(int)pt.get_y());
				prevxx = xx;
			}
			}
			//}
//		}
		
	return 0;
}
//draw smaller version with curved sides (e.g. dungeon tower)
int PixmapTexture::drawcurved3(Display **dpy, Window *w, int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	double fracx = _w/_enlargew, fracy = _h/_enlargeh;
	for (int xx = 0; xx < _w; xx++) { 
		for (int yy = 0; yy < _h; yy++) {
				Point pt(xx*fracx,yy*fracy,1);
				Point p2(xx,yy,1);
				//_alpha += 5;//0.9;
				_alpha += 5;//0.9;
				//Point pt(((int)((xx*_alpha/_enlargew))),((int)((yy*_alpha/_enlargeh))),1);
				unsigned long color = 65000;
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				XDrawLine(*dpy, *w, gc,offsetx+xx/_alpha,offsety+yy/_alpha,offsetx+xx,offsety+yy);
					
					
				//unsigned long color = 65000;
				unsigned long color2 = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
				values.foreground = color2;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				//if (_globalalpha > 1) {
				for (int j = prevx; j < xx*_alpha/_enlargew; j++) {
				for (int k = prevy; k < yy*_alpha/_enlargeh; k++) {
					Point pt2((int)((xx+j)*_alpha/_enlargew),(int)((yy)*_alpha/_enlargeh),1);
					XDrawLine(*dpy, *w, gc,offsetx+(int)pt2.get_x(),offsety+(int)pt2.get_y(),offsetx+(int)pt2.get_x(),offsety+(int)pt2.get_y());
					Point pt3((int)((xx)*_alpha/_enlargew),(int)((yy+k)*_alpha/_enlargeh),1);
					XDrawLine(*dpy, *w, gc,offsetx+(int)pt3.get_x(),offsety+(int)pt3.get_y(),offsetx+(int)pt3.get_x(),offsety+(int)pt3.get_y());
				}
				}
				//}
				prevy = yy*_alpha/_enlargeh;
				prevx = xx*_alpha/_enlargew;
			}
			}
			//}
//		}
		
	return 0;
}

//put big pixmap translated through Z axis
int PixmapTexture::drawcurved2(Display **dpy, Window *w, int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	double fracx = _w/_enlargew, fracy = _h/_enlargeh;
	for (int xx = 0; xx < _w; xx++) { 
		for (int yy = 0; yy < _h; yy++) {
				//Point p1((*vi)[i-1]);
				//Point p2((*vi)[i]);
				//Point p1(_polygons[0][0].get_x(),_polygons[0][0].get_y(),1);
				Point pt(xx*fracx,yy*fracy,1);
				Point p2(xx,yy,1);
				//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
				//pt = pt.scaley(angle);//_pixmaptexture.get_alpha());
				//_globalalpha +=  _alpha;
				//_alpha += 5;//0.9;
				//Point pt(((int)((xx*_alpha/_enlargew))),((int)((yy*_alpha/_enlargeh))),1);
			//	//_global += 1;
	
					
				//unsigned long color = 65000;
				unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				//if (_globalalpha > 1) {
				for (int j = prevx; j < xx*_alpha/_enlargew; j++) {
				for (int k = prevy; k < yy*_alpha/_enlargeh; k++) {
					Point pt2((int)((xx+j)*_alpha/_enlargew),(int)((yy)*_alpha/_enlargeh),1);
        				Matrix3 rotmz = ray3d::rotatez(thetaz);
					Vector3 prot(pt2.get_x(),pt2.get_y(),pt2.get_z());
					prot = rotmz*prot;
					///////XDrawLine(*dpy, *w, gc,offsetx+(int)pt2.get_x(),offsety+(int)pt2.get_y(),offsetx+(int)pt2.get_x(),offsety+(int)pt2.get_y());
					XDrawLine(*dpy, *w, gc,offsetx+(int)prot[0],offsety+(int)prot[1],offsetx+(int)prot[0],offsety+(int)prot[1]);
					Point pt3((int)((xx)*_alpha/_enlargew),(int)((yy+k)*_alpha/_enlargeh),1);
					prot = Vector3(pt3.get_x(),pt3.get_y(),pt3.get_z());
					prot = rotmz*prot;
					///////XDrawLine(*dpy, *w, gc,offsetx+(int)pt3.get_x(),offsety+(int)pt3.get_y(),offsetx+(int)pt3.get_x(),offsety+(int)pt3.get_y());
					XDrawLine(*dpy, *w, gc,offsetx+(int)prot[0],offsety+(int)prot[1],offsetx+(int)prot[0],offsety+(int)prot[1]);
				}
				}
				//	_global = 0;
				//	_globalalpha = 0;
				//}
				prevy = yy*_alpha/_enlargeh;
				prevx = xx*_alpha/_enlargew;
			}
			}
			//}
//		}
		
	return 0;
}
//draw smaller version, straight walls, Quake
int PixmapTexture::drawsmall(Display **dpy, Window *w,int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	double fracx = _w/5, fracy = _h/5;//FIXME1 fixed 10
	int dx=0,dy=0;
	for (int yy = 0; yy < _h; yy += fracy) {
		for (int xx = 0; xx < _w; xx += fracx) { 
			Point pt(xx,yy,1);
				//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
				_alpha += 5;//0.9;
				_beta += 5;//0.9;
					
				//unsigned long color = 65000;
				unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				XDrawLine(*dpy, *w, gc,
				offsetx+(int)dx,
				offsety+(int)dy,
				offsetx+(int)dx,
				offsety+(int)dy);
				dx ++;
			}
			dy ++;
			}
			//}
//		}
		
	return 0;
}
//draw smaller version, straight walls, Quake and rotate
int PixmapTexture::drawsmallandrotate(Display **dpy, Window *w,int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;
	//_alpha = 5;
	//_beta = 5;
	double prevx=0,prevy=0;
	double fracx = _w/_alpha, fracy = _h/_beta;//FIXME1 fixed 10
	int dx=0,dy=0;
	for (int yy = 0; yy < _h; yy += fracy) {
		for (int xx = 0; xx < _w; xx += fracx) { 
			Point pt(xx,yy,1);
				//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
				_alpha += _alpha;//0.9;
				_beta += _beta;//0.9;
					
				//unsigned long color = 65000;
				unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				XDrawLine(*dpy, *w, gc,
				offsetx+(int)dx,
				offsety+(int)dy,
				offsetx+(int)dx,
				offsety+(int)dy);
				dx ++;
			}
			dy ++;
			}
			//}
//		}
		
	return 0;
}
//draw enlargement version/
int PixmapTexture::drawbig(Display **dpy, Window *w,int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	_alpha = 5;
	_beta = 5;
	double fracx = _alpha, fracy = _beta;//FIXME1 fixed 10
	int dx=0,dy=0;
	for (int yy = 0; yy < _h*_beta; yy ++) {
		for (int xx = 0; xx < _w*_alpha; xx ++) { 
			Point pt(xx/_alpha,yy/_beta,1);
			//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
			_alpha += 5;//0.9;
			_beta += 5;//0.9;
					
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
			values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        		gc = XCreateGC(*dpy, *w, valuemask, &values);
			XDrawLine(*dpy, *w, gc,
				offsetx+(int)xx/_alpha,
				offsety+(int)yy/_beta,
				offsetx+(int)xx/_alpha,
				offsety+(int)yy/_beta);
				dx ++;
			}
			dy ++;
			}
		
	return 0;
}
//draw enlarged version 2 (xpm chars get projected towards you and the pic enlarges)
int PixmapTexture::drawbigger(Display **dpy, Window *w,int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	_alpha = 5;
	_beta = 5;
	double fracx = _alpha, fracy = _beta;//FIXME1 fixed 10
	int dx=0,dy=0;
	for (int yy = 0; yy < _h*_beta; yy ++) {
		for (int xx = 0; xx < _w*_alpha; xx ++) { 
			Point pt(xx/_alpha,yy/_beta,1);
			//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
			values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        		gc = XCreateGC(*dpy, *w, valuemask, &values);
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			Vector3 prot(xx/_alpha,yy/_beta,1);
			//prot = rotmx*prot;
			//prot = rotmy*prot;
			prot = rotmx*prot;
			if (color != 0)//alpha channel black
			XDrawLine(*dpy, *w, gc,
				offsetx+(int)xx,
				offsety+(int)yy,
				offsetx+(int)xx,
				offsety+(int)yy);
			/*XDrawLine(*dpy, *w, gc,
				offsetx+(int)prot[0],
				offsety+(int)prot[1],
				offsetx+(int)prot[0],
				offsety+(int)prot[1]);
			*/	dx ++;
			}
			dy ++;
			}
		
	return 0;
}
int PixmapTexture::drawbiggerandrotate(Display **dpy, Window *w,int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	_alpha = 5;
	_beta = 5;
	double fracx = _alpha, fracy = _beta;//FIXME1 fixed 10
	int dx=0,dy=0;
	for (int yy = 0; yy < _h*_beta; yy ++) {
		for (int xx = 0; xx < _w*_alpha; xx ++) { 
			Point pt(xx/_alpha,yy/_beta,1);
			//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
			values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        		gc = XCreateGC(*dpy, *w, valuemask, &values);
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			thetax += 0.001;
			thetay += 0.001;
			thetaz += 0.001;
			Vector3 prot(xx/_alpha,yy/_beta,1);
			//prot = rotmz*prot;
			//prot = rotmy*prot;
			prot = rotmx*prot;
			if (color != 0)//alpha channel black
			/*XDrawLine(*dpy, *w, gc,
				offsetx+(int)xx,
				offsety+(int)yy,
				offsetx+(int)xx,
				offsety+(int)yy);
			*/XDrawLine(*dpy, *w, gc,
				offsetx+(int)prot[0],
				offsety+(int)prot[1],
				offsetx+(int)prot[0],
				offsety+(int)prot[1]);
				dx ++;
			}
			dy ++;
			}
		
	return 0;
}

int PixmapTexture::initdraw1(PixmapTextureModel& model)
{

	model.empty_points();

	double prevx=0,prevy=0;
	_alpha = 5;
	_beta = 5;
	double fracx = _alpha, fracy = _beta;//FIXME1 fixed 10
	int dx=0,dy=0;
	for (int yy = 0; yy < _h*_beta; yy ++) {
		for (int xx = 0; xx < _w*_alpha; xx ++) { 
			Point pt(xx/_alpha,yy/_beta,1);
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
        	/*	Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			thetax += 0.001;
			thetay += 0.001;
			thetaz += 0.001;
			Vector3 prot(xx/_alpha,yy/_beta,1);
			//prot = rotmz*prot;
			//prot = rotmy*prot;
			prot = rotmx*prot;
		*/
		if (color != 0)//alpha channel black
			/*XDrawLine(*dpy, *w, gc,
				offsetx+(int)xx,
				offsety+(int)yy,
				offsetx+(int)xx,
				offsety+(int)yy);
			*//*XDrawLine(*dpy, *w, gc,
				offsetx+(int)prot[0],
				offsety+(int)prot[1],
				offsetx+(int)prot[0],
				offsety+(int)prot[1]);
			*/	dx ++;
			//model.addpoint(Point(prot[0],prot[1],prot[2],color));
			model.addpoint(Point(xx/_alpha,yy,1,color));
			}
			dy ++;
		}
		
	return 0;
}
//enlarge with _alpha, _beta and rotate with thetax thetay,thetaz matrices
int PixmapTexture::rotatemodel(PixmapTextureModel& model)
{
	model.empty_points();

	int i = 0;
	for (int yy = 0; yy < _h*_beta; yy ++) {
		for (int xx = 0; xx < _w*_alpha; xx ++) { 
			Point pt(xx/_alpha,yy/_beta,1);
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			thetax += 0.001;
			thetay += 0.001;
			thetaz += 0.001;
			Vector3 prot(xx,yy,1);
			//prot = rotmz*prot;
			//prot = rotmy*prot;
			prot = rotmx*prot;
			Point p(prot[0],prot[1],prot[2],color);
			if (color != 0)//alpha channel black
				model.addpoint(Point(p[0],p[1],p[2],p.get_color()));
		}
	}
	return 0;
}
//draw enlarged version with point vector3 proj/rot matrix.
int PixmapTexture::drawenlargeandrotate(Display **dpy, Window *w,int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	_alpha = 5;
	_beta = 5;
	double fracx = _alpha, fracy = _beta;//FIXME1 fixed 10
	int dx=0,dy=0;
	for (int yy = 0; yy < _h*_beta; yy ++) {
		for (int xx = 0; xx < _w*_alpha; xx ++) { 
			Point pt(xx/_alpha,yy/_beta,1);
			//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
			values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        		gc = XCreateGC(*dpy, *w, valuemask, &values);
			thetax *= 1.5;
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			Vector3 prot(xx,yy,1);
			//prot = rotmx*prot;
			XDrawLine(*dpy, *w, gc,
				offsetx+(int)prot[0],
				offsety+(int)prot[1],
				offsetx+(int)prot[2],
				offsety+(int)yy);
				dx ++;
			}
			dy ++;
			}
		
	return 0;
}
//draw rotation of pixmap
int PixmapTexture::drawenlargeandrotate2(Display **dpy, Window *w,int offsetx, int offsety)
{

/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

			//for (int i = 0; i < 4; i++) {
			//FIXME int ww = get_w() + get_w() * _alpha;
			//int hh = get_h() + get_h() * _alpha;

	double prevx=0,prevy=0;
	_alpha = 1;
	_beta = 1;
	double fracx = _alpha, fracy = _beta;//FIXME1 fixed 10
	int dx=0,dy=0;
	for (int yy = 0; yy < _h*_beta; yy ++) {
		for (int xx = 0; xx < _w*_alpha; xx ++) { 
			Point pt(xx/_alpha,yy/_beta,1);
			//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
			values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        		gc = XCreateGC(*dpy, *w, valuemask, &values);
			thetax *= 1.5;
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			Vector3 prot(xx,yy,1);
			prot = rotmx*prot;
			prot = rotmy*prot;
			prot = rotmz*prot;
			XDrawLine(*dpy, *w, gc,
				offsetx+(int)prot[0],
				offsety+(int)prot[1],
				offsetx+(int)prot[2],
				offsety+(int)yy);
				dx ++;
			}
			dy ++;
			}
		
	return 0;
}
//draw - smaller version of pixmap
int PixmapTexture::drawsmaller(Display **dpy, Window *w, int offsetx, int offsety, double a, double b)
{
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);

	//NOTE: do not draw polygon lines, rather texture in between 
	//NOTE: polygons are fixed at 4 points
//	ray3d::Polygon poly;
/*	poly += ray3d::Point(20,20,20);
	poly += ray3d::Point(102,102,102);
	poly += ray3d::Point(120,120,120);
	poly += ray3d::Point(20,20,20);
	_polygons.push_back(poly);
*/	double dx = 0, dy = 0;
	for (int yy = 0; yy < _w; yy += b) {
		for (int xx = 0; xx < _h; xx += a) { 
			Point pt(xx,yy,1);
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
			values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			Vector3 prot(dx,dy,1);
			prot = rotmz*prot;
        		gc = XCreateGC(*dpy, *w, valuemask, &values);
			//XDrawLine(*dpy, *w, gc,dx+offsetx,dy+offsety,dx+offsetx,dy+offsety);
			XDrawLine(*dpy, *w, gc,prot.get_x()+offsetx,prot.get_y()+offsety,prot.get_x()+offsetx,prot.get_y()+offsety);
			dx++;
			}
			dy++;
			}
		
	return 0;
}

int PixmapTexture::draw2(Display **dpy, Window *w)
{
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

	const std::string filename("./post.xpm");
	//NOTE: do not draw polygon lines, rather texture in between 
	//NOTE: polygons are fixed at 4 points
	ray3d::Polygon poly;
	poly += ray3d::Point(2,2,2);
	poly += ray3d::Point(120,120,120);
	poly += ray3d::Point(20,20,20);
	poly += ray3d::Point(2,2,2);
	_polygons.push_back(poly);
	for (PolygonVector::iterator vi = _polygons.begin(); vi != _polygons.end(); vi++ ) {
			for (int i = 1; i < 5; i++) {
				Point p1((*vi)[i-1]);
				Point p2((*vi)[i]);
			
				Point p3(p1.scalex(_alpha));	
				unsigned long color = _xpmimage.getpixel(p3.get_x(), p3.get_y());
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				XDrawLine(*dpy, *w, gc, p3.get_x(),p3.get_y(),p2.get_x(),p2.get_y());
			}
		}
*/		
	return 0;
}



} // namespace ray3d

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaPixmapTextureModel.h"
#include<cstdlib>
#include<iostream>

namespace ray3d {	
int PixmapTextureModel::draw(Display **dpy, Window *w, int offsetx, int offsety)
{
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/
	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);

	//if (_points.empty())
	//NOTE init points
	_pixmaptexture.rotatemodel(*this);

	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++) {
		values.foreground = (*vi).get_color();
        	gc = XCreateGC(*dpy, *w, valuemask, &values);
		
		XDrawLine(*dpy,*w,gc,(*vi).get_x()+offsetx,(*vi).get_y()+offsety,(*vi).get_x()+offsetx,(*vi).get_y()+offsety);
	}
	return 0;
}

int PixmapTextureModel::draw2(Display **dpy, Window *w)
{
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
/*	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

	const std::string filename("./post.xpm");
	//NOTE: do not draw polygon lines, rather texture in between 
	//NOTE: polygons are fixed at 4 points
	ray3d::Polygon poly;
	poly += ray3d::Point(20,20,20);
	poly += ray3d::Point(102,102,102);
	poly += ray3d::Point(120,120,120);
	poly += ray3d::Point(20,20,20);
	_polygons.push_back(poly);
	//for (PolygonVector::iterator vi = _polygons.begin(); vi != _polygons.end(); vi++ ) {
			//for (int i = 0; i < 4; i++) {
			for (int xx = 0; xx < _pixmaptexture.get_w(); xx++) { 
			for (int yy = 0; yy < _pixmaptexture.get_h(); yy++) {
				//Point p1((*vi)[i-1]);
				//Point p2((*vi)[i]);
				Point p1(_polygons[0][0].get_x(),_polygons[0][0].get_y(),1);
				Point p2(xx,yy,1);
				//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
				//pt = pt.scaley(angle);//_pixmaptexture.get_alpha());
				_alpha -= 0.001;
				Point pt(xx*(angle),yy*(angle),1);
				//unsigned long color = 65000;//_pixmaptexture.get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
				unsigned long color = _pixmaptexture.get_xpmimage().getpixel((int)pt.get_x()%24, (int)pt.get_y()%24);
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				/////XDrawLine(*dpy, *w, gc, p1.get_x()+(int)pt.get_x(),p1.get_y()+(int)pt.get_y(),p1.get_x()+(int)pt.get_x(),p1.get_y()+(int)pt.get_y());
				XDrawLine(*dpy, *w, gc,20+(int)pt.get_x(),20+(int)pt.get_y(),20+(int)pt.get_x(),20+(int)pt.get_y());
			}
			}
			//}
//		}
*/		
	return 0;
}



} // namespace ray3d

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaPixmapTextureModelFill.h"
#include<cstdlib>
#include<iostream>

namespace ray3d {	
int PixmapTextureModelFill::draw(Display **dpy, Window *w)
{
	#define NIL (0)
/*  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);
/*
	const std::string filename("./post.xpm");
	//NOTE: do not draw polygon lines, rather texture in between 
	//NOTE: polygons are fixed at 4 points
	ray3d::Polygon poly;
	poly += ray3d::Point(20,20,20);
	poly += ray3d::Point(102,102,102);
	poly += ray3d::Point(120,120,120);
	poly += ray3d::Point(20,20,20);
	_polygons.push_back(poly);
	//for (PolygonVector::iterator vi = _polygons.begin(); vi != _polygons.end(); vi++ ) {
			//for (int i = 0; i < 4; i++) {
			for (int xx = 0; xx < _pixmaptexture.get_w(); xx++) { 
			for (int yy = 0; yy < _pixmaptexture.get_h(); yy++) {
				//Point p1((*vi)[i-1]);
				//Point p2((*vi)[i]);
				Point p1(_polygons[0][0].get_x(),_polygons[0][0].get_y(),1);
				Point p2(xx,yy,1);
				//Point pt = p2.scalex(angle);//_pixmaptexture.get_alpha());
				//pt = pt.scaley(angle);//_pixmaptexture.get_alpha());
				angle -= 0.001;
				Point pt(xx*(angle),yy*(angle),1);
				//unsigned long color = 65000;//_pixmaptexture.get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
				unsigned long color = _pixmaptexture.get_xpmimage().getpixel((int)pt.get_x()%24, (int)pt.get_y()%24);
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				/////XDrawLine(*dpy, *w, gc, p1.get_x()+(int)pt.get_x(),p1.get_y()+(int)pt.get_y(),p1.get_x()+(int)pt.get_x(),p1.get_y()+(int)pt.get_y());
				XDrawLine(*dpy, *w, gc,20+(int)pt.get_x(),20+(int)pt.get_y(),20+(int)pt.get_x(),20+(int)pt.get_y());
			}
			}
			//}
//		}
*/		
	return 0;
}



} // namespace ray3d

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaPixmapTextureModelRotate.h"
#include<cstdlib>
#include<iostream>

namespace ray3d {	
int PixmapTextureModelRotate::draw(Display **dpy, Window *w, int offsetx, int offsety)
{
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/
	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);

	//if (_points.empty())
	//NOTE init points
	_pixmaptexture.rotatemodel(*this);

	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++) {
		values.foreground = (*vi).get_color();
        	gc = XCreateGC(*dpy, *w, valuemask, &values);
		
		XDrawLine(*dpy,*w,gc,(*vi).get_x()+offsetx,(*vi).get_y()+offsety,(*vi).get_x()+offsetx,(*vi).get_y()+offsety);
	}
	return 0;
}

}//namespae ray3d
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaPoint.h"
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaPolygon.h"

namespace ray3d {

int Polygon::draw(Display **dpy, Window *w)
{
	#define NIL (0)
	std::vector<Point>::iterator pi = _points.begin();
      	GC gc = XCreateGC(*dpy, *w, 0, NIL);
	for (std::vector<Point>::iterator vi = _points.begin()++; vi != _points.end(); vi++ ) {
		XDrawLine(*dpy, *w, gc, (*vi).get_x(),(*vi).get_y(),(*pi).get_x(),(*pi).get_y());
		pi = vi;
	}
	return 0;
}

}
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaPolygonModel.h"
#include<cstdlib>
#include<cstring>

namespace ray3d {	

int PolygonModel::draw(Display **dpy, Window *w)
{

	for (PolygonVector::iterator vi = _polygons.begin(); vi != _polygons.end(); vi++ ) {
		(*vi).draw(dpy, w);
	}
	return 0;
}

int PolygonModel::filein(std::string const& filename)
{
	std::ifstream *ifs = new std::ifstream(filename.c_str());
	PointVector v;
	PointVector pv;
	Polygon poly;	
	for (; !ifs->eof(); ) {
		char *buf = new char[1024];//FIXME fixed size
		char *buf2 = new char[1024];//FIXME fixed size
		char *buf3 = new char[1024];//FIXME fixed size
		memset(buf,0,1024);
		memset(buf2,0,1024);
		memset(buf3,0,1024);
		(*ifs) >> buf;
		if (ifs->eof()) return -1; else (*ifs) >> buf2;
		if (ifs->eof()) return -1; else (*ifs) >> buf3;
		pv.push_back(Point(std::atof(buf),std::atof(buf2),std::atof(buf3)));
		v.push_back(Point(std::atof(buf),std::atof(buf2),std::atof(buf3)));
		poly += Point(std::atof(buf),std::atof(buf2),std::atof(buf3));
		
		/*for (PVec::iterator vi = v.begin(); vi != v.end(); vi++) {
			std::cout<< "*vi="<<(*vi).get_x()<<" buf="<< std::string(buf).c_str() <<std::endl;
			if ((*vi) == Point(std::atof(buf),std::atof(buf2),std::atof(buf3))) {
				_polygons.push_back(poly);
				poly = Polygon();
				v = PVec();
				pv = PVec();
			}
		}*/
		delete [] buf;
		delete [] buf2;
		delete [] buf3;
	}
	_polygons.push_back(poly);

	return 0;
}

int PolygonModel::fileout(std::string const& filename)
{
	char buf[1024];
	std::ofstream *ofs = new std::ofstream(filename.c_str());
	for (int i = 0; i < _polygons.size(); i++)
	for (int j = 0; j < _polygons[i].size(); j++) {
		sprintf(buf, "%e ", (double)(_polygons[i][j][0]));
		(*ofs) << buf; 
		sprintf(buf, "%e ", (double)(_polygons[i][j][1]));
		(*ofs) << buf; 
		sprintf(buf, "%e ", (double)(_polygons[i][j][2]));
		(*ofs) << buf; 
	}	
	return 0;
}

int PolygonModel::raytrace(Display **dpy, Window *w)
{ //FIXME
}

int PolygonModel::dithersunray(Display **dpy, Window *w)
{//FIXME
}

} // namespace ray3d

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "RayMantaProducerSystem.h"
#include <cstdlib>
#include <iostream>

Genes RayMantaProducerSystem::initcrossovergenes(int n) 
{

	Genes cg(n);

	for (int i = 0; i < n; i++) {

		cg[i] = (::rand());

	}
	
	return cg;
}

Genes RayMantaProducerSystem::mutate(int index)
{

	for (int i = 0; i < genes.size(); i++) {

		genes[i] = ::rand();

	}
	return genes;	
}
Genes RayMantaProducerSystem::crossover(int index1, int index2)
{
	crossovergenes = initcrossovergenes(index2-index1);
	//crossover from index1 to index2

	if (index1 > crossovergenes.size() || index2 > crossovergenes.size())
		return genes;

	for (int i = index1; i < index2; i++) {
		genes[i] = crossovergenes[i];
	}
	return genes;
}
int RayMantaProducerSystem::draw(RayMantaBase const& rmb)
{
	Window w = window->getWindow(); 
//        GC gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);

	for (int i = 0; i < SCREENH; i++) {
	for (int j = 0; j < SCREENW; j++) {

	XGCValues values;
	unsigned long color = genes[j+i*SCREENW];
	values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = color;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*(dpyb.get_display()), w, valuemask, &values);
        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,(int)i,(int)j,(int)i,(int)j);

	}
	}
	return 0;
}
void RayMantaProducerSystem::eventloop(XEvent *e)
//int RayMantaProducerSystem::run(int ngenes)
{
	long int r = ::random();
	int index = r % genes.size();
	long int r2 = ::random();
	int index2 = r2 % genes.size();

	//do mutation or crossover for fitness eval
	mutate(index);
	//crossover(index,index2);
	std::cout<<"fitness="<<fitness()<<std::endl;
  #define NIL (0)
  int events;
  GC gc;
  gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
  const char * test = "XMantaRay - Graphics Producer framework";
  XmbDrawString(*(dpyb.get_display()), window->getTitleWindow(), fontset, gc, 20, 10, test, strlen(test));
  draw(*this);
  
  for (int i = 0; i < 1000; i++) {//calibrator
    if (events = XPending(*(dpyb.get_display()))) { 
      //XEvent e;
      XNextEvent(*(dpyb.get_display()), e);
      printf("got event %d from number of events = %d\n", e->type, events);
	process_event(e);
	XFillRectangle(*(dpyb.get_display()), window->getTitleWindow(), gc,0,0,800,20);
	XFillRectangle(*(dpyb.get_display()), window->getWindow(), gc,0,0,800,600);
    	//XSync(*dpy, 0);
	}
	
  }
	XFlush(*(dpyb.get_display()));
/*
  #define NIL (0)
  int events;
  GC gc;
  gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
  const char * test = "XMantaRay - Graphics producer system ";
  XmbDrawString(*(dpyb.get_display()), window->getTitleWindow(), fontset, gc, 20, 10, test, strlen(test));
  	draw(*this);
  
  for (int i = 0; i < 1000; i++) {//calibrator
    if (events = XPending(*(dpyb.get_display()))) { 
      //XEvent e;
      XNextEvent(*(dpyb.get_display()), e);
      printf("got event %d from number of events = %d\n", e->type, events);
	process_event(e);
    	//XSync(*dpy, 0);
	}
	
  }
	XFlush(*(dpyb.get_display()));
*/	return;
}
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "RayMantaRayTracer.h"
#include "Xmanager.h"
#include "RayMantaWindow.h"
#include "RayMantaEngine.h"
#include "RayMantaMatrix3.h"
#include "RayMantaSphereModel.h"

static double theta1 = 1.5;
static double theta12 = 2.5;
static double theta13 = 3.5;
int RayMantaRayTracer::draw(RayMantaBase const& rmb)
{
	Window w = window->getWindow(); 
        GC gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
	//3D rotation code
        ray3d::SphereModel sm(dpyb.get_display(),&w,&gc);

	sm.generatesphere(dpyb.get_display(), &w);
	sm.draw(dpyb.get_display(),&w);
/*        ray3d::Vector3 v1(0,0,0), v2(100,100,100);
        ray3d::Matrix3 rotmx,rotmy,rotmz;
        //rotm = ray3d::Matrix3(e.initrotatex(0.1*k));
        rotmx = ray3d::rotatex(theta1);
        rotmy = ray3d::rotatey(theta12);
        rotmz = ray3d::rotatez(theta13);

//        v2 = rotmx*v2;
//        v2 = rotmy*v2;
//        v2 = rotmz*v2;
        //std::cout<<"matrix x22>"<<rotm.get_x22()<<std::endl;
        //XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,0,0,100,100);
        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,(int)v1.get_x(),(int)v1.get_y(),(int)v2.get_x(),(int)v2.get_y());
*/
	return 0;
}


int RayMantaRayTracer::draw2(Display **dpy, int const& k)
{
	Window w = window->getWindow(); 
        GC gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
	//3D rotation code
        ray3d::SphereModel sm(dpy,&w,&gc);

	sm.generatesphere(dpy, &w);
//	sm.draw(dpy,&w);
/*        ray3d::Vector3 v1(0,0,0), v2(100,100,100);
        ray3d::Matrix3 rotmx,rotmy,rotmz;
        //rotm = ray3d::Matrix3(e.initrotatex(0.1*k));
        rotmx = ray3d::rotatex(theta1);
        rotmy = ray3d::rotatey(theta12);
        rotmz = ray3d::rotatez(theta13);

//        v2 = rotmx*v2;
//        v2 = rotmy*v2;
//        v2 = rotmz*v2;
        //std::cout<<"matrix x22>"<<rotm.get_x22()<<std::endl;
        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,0,0,100,100);
        XDrawLine(*(dpyb.get_display()),window->getWindow(),gc,(int)v1.get_x(),(int)v1.get_y(),(int)v2.get_x(),(int)v2.get_y());
*/
	return 0;
}

void RayMantaRayTracer::eventloop(RayMantaBase& rmb, XEvent *e) 
{
  #define NIL (0)
  int events;
  GC gc;
  gc = XCreateGC(*(dpyb.get_display()), window->getWindow(), 0, NIL);
  const char * test = "XMantaRay - raytracer";
  XmbDrawString(*(dpyb.get_display()), window->getTitleWindow(), fontset, gc, 20, 10, test, strlen(test));
	//if (RayMantaRayTracer* rm = dynamic_cast<RayMantaRayTracer*>(&rmb)) {
  	draw(*this);
	//} else if (RayManta* rm = dynamic_cast<RayManta*>(&rmb)) {
  	//	rm->draw(*this);
	//}
  
  for (int i = 0; i < 1000; i++) {//calibrator
    if (events = XPending(*(dpyb.get_display()))) { 
      //XEvent e;
      XNextEvent(*(dpyb.get_display()), e);
      printf("got event %d from number of events = %d\n", e->type, events);
	process_event(e);
    	//XSync(*dpy, 0);
	}
	
  }
	XFlush(*(dpyb.get_display()));
}

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaSphereModel.h"
#include<cstdlib>

namespace ray3d {	

int SphereModel::draw(Display **dpy, Window *w)
{
	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

	for (std::vector<Point>::iterator vi = _spherepoints.begin(); vi != _spherepoints.end(); vi++ ) {
		XDrawLine(*dpy, *w, gc, (*vi).get_x(),(*vi).get_y(),(*vi).get_x(),(*vi).get_y());

	}
	return 0;
}


int SphereModel::generatesphere(Display **dpy, Window *w)
{
#define NIL (0)
   GC gc = XCreateGC(*dpy, *w, 0, NIL);

  // sphere init
  double r = 100;
  Point center(100,100,100);
  int xx,yy,zz;
  //draw sphere
  for (zz = -1; zz< 1; zz++) {
  for (xx = -100; xx < 100; xx++) {
  for (yy = -100; yy < 100; yy++) {
	Point p(xx,yy,zz);
	if (xx*xx  + yy*yy + zz*zz <= r*r) {
		int txx = xx + center.get_x();
		int tyy = yy + center.get_y();
		int tzz = zz + center.get_z();
  		XDrawLine(*dpy, *w, gc, txx,tyy,txx,tyy);
		_spherepoints.push_back(p);
	}
  }
  }
  }

  //draw sphere
/*
  for (zz = -1; zz< 1; zz++) {
  for (xx = -100; xx < 100; xx++) {
  for (yy = -100; yy < 100; yy++) {
      	GC gc = XCreateGC(dpy, w, 0, NIL);
	Point p(xx,yy,zz);
	if (xx*xx  + yy*yy + zz*zz <= r*r) {
		int txx = xx + center.get_x();
		int tyy = yy + center.get_y();
		int tzz = zz + center.get_z();
  		XDrawLine(dpy, w, gc, txx,tyy,txx,tyy);
	}
  }
  }
  }
*/
}

int SphereModel::raycast(Display **dpy, Window *w)
{

  #define NIL (0)

  std::vector<Point> spherepoints;
  double r = 100;
  Point center(100,100,100);
  int xx, yy, zz;

  for (zz = -100; zz< 200; zz++) {
  for (xx = -100; xx < 800; xx++) {
  for (yy = -100; yy < 600; yy++) {

 	//Point s(xx*10,yy*10,zz*10);
  	Point s(xx,yy,zz);
  	Point v = s - center; 
  	Point d(1,1,0);
  	//double t = (2*v*d + std::sqrt(2*v*d-4(v*v-r*r))/2 
  	double discr = (v*d)*(v*d) - (v*v - r*r);
  	double t1 = - (v*d) - std::sqrt((v*d)*(v*d) - (v*v - r*r));
  	double t2 = - (v*d) + std::sqrt((v*d)*(v*d) - (v*v - r*r));

	_spherepoints.push_back(Point(t1,t2,1));
	_spherepoints.push_back(Point(t2,t1,1));
	//FIXME luminosity with proximity between t1 and t2
//  	if (discr >= 0) 
	{
      		GC gc = XCreateGC(*dpy, *w, 0, NIL);
  		XDrawLine(*dpy, *w, gc, 0,0,t1,t2);//FIXME t1 0
  		XDrawLine(*dpy, *w, gc, 0,0,t2,t1);//FIXME t1 0
	}

  }	
  }
  }
}

int SphereModel::raytrace(Display **dpy, Window *w, Point const& p)
{

  #define NIL (0)

  generatesphere(dpy,w); 
	
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
	int k = 0;
  for (std::vector<Point>::iterator vi = _spherepoints.begin(); vi != _spherepoints.end(); vi++,k++ ) {
	//normalize
	values.foreground = (1400*k)%65665;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = (2048*k)%65665;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
	Point N(0,const_cast<Point&>(p).get_y(),0);
	Point L(p);
	
	double d = 0.1;

	N.normalize();
	L.normalize();

	Point NL(N-L);	
	double A = NL.dist(N);
	double B = NL.dist(L);
	//now sin(alpha) ~= alpha
	double alpha = 0;
	alpha = B*1/A; 

	double inner = N*L;
	int convolution = inner * std::cos(alpha);

	XDrawLine(*dpy,*w, gc,
			const_cast<Point&>(p).get_x(),
			const_cast<Point&>(p).get_y(),
			const_cast<Point&>(p).get_x(),
			const_cast<Point&>(p).get_y());
	//FIXME modify color
  }	
	
}

int SphereModel::raytrace2(Display **dpy, Window *w, Point const& p)
{

  generatesphere(dpy,w); 
	
}
int SphereModel::dithersunray(Display **dpy, Window *w)
{
  int xx,yy,zz;
  double r = 100;
  Point center(100,100,100);
  for (zz = 0; zz< 200; zz++) {
  for (xx = 0; xx < 200; xx++) {
  for (yy = 0; yy < 200; yy++) {
  	//Point s(xx*10,yy*10,zz*10);
  	Point s(xx,yy,zz);
  	Point v = s - center; 
  	Point d(1,1,0);
  	//double t = (2*v*d + std::sqrt(2*v*d-4(v*v-r*r))/2 
  	double discr = (v*d)*(v*d) - (v*v - r*r);
  	double t1 = - (v*d) - std::sqrt((v*d)*(v*d) - (v*v - r*r));
  	double t2 = - (v*d) + std::sqrt((v*d)*(v*d) - (v*v - r*r));

	_spherepoints.push_back(Point(t1,t2,1));
	_spherepoints.push_back(Point(t2,t1,1));
	//FIXME luminosity with proximity between t1 and t2
  	//if (discr >= 0) 
	{
      		GC gc = XCreateGC(*dpy, *w, 0, NIL);
  		XDrawLine(*dpy, *w, gc, 0,0,t1,t2);//FIXME t1 0
  		XDrawLine(*dpy, *w, gc, 0,0,t2,t1);//FIXME t1 0
	}
}}}
//sleep(10);
}

int SphereModel::drawsunray(Display **dpy, Window *w)
{
  for (int i = 0; i < _spherepoints.size(); i++) {
  	//GC gc = XCreateGC(dpy, w, gc_mask, &values);
  	//GC gc2 = XCreateGC(dpy, w, gc_mask2, &values2);
      	GC gc = XCreateGC(*dpy, *w, 0, NIL);

	double d = Point(0,0,0).dist(_spherepoints[i]);
	int x1 = _spherepoints[i].get_x();
	int y1 = _spherepoints[i].get_y();
	int x2 = _spherepoints[i].get_x();
	int y2 = _spherepoints[i].get_y();
//	if (d < 10)
	XDrawLine(*dpy,*w,gc, x1,y1,x2,y2);	
//	else
//	XDrawLine(*dpy,*w,gc, x1,y1,x2,y2);	
  }
	return 0; 
}

} // namespace ray3d

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaSpiderModel.h"
#include<cstdlib>
#include<iostream>

namespace ray3d {	
int SpiderModel::draw(Display **dpy, Window *w, int offsetx, int offsety)
{
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
*/
	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);

	//if (_points.empty())
	//NOTE init points
//	_pixmaptexture.rotatemodel(*this);

	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++) {
		values.foreground = (*vi).get_color();
        	gc = XCreateGC(*dpy, *w, valuemask, &values);
		
		XDrawLine(*dpy,*w,gc,(*vi).get_x()+offsetx,(*vi).get_y()+offsety,(*vi).get_x()+offsetx,(*vi).get_y()+offsety);
	}
	return 0;
}

}//namespae ray3d
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaSpiderTexture.h"
#include "RayMantaSpiderModel.h"
#include "RayMantaMatrix3.h"
#include<cstdlib>

namespace ray3d {

/*
* NOTE : You map the _xpmimage 
* (xpm XImage, see file RayMantaPixmapImage.h/.cc)
* onto the walls, curved,dungeon tower and straight walls.
*/	
//main draw method

int SpiderTexture::initdraw(SpiderModel& model)
{
	thetax = 1.5;
	thetay = 2.5;
	thetaz = 3.5;

	initdraw1(model);//,/*offsetx+*/100,/*offsety+*/100);

}

int SpiderTexture::initdraw1(SpiderModel& model)
{

	model.empty_points();
	initspiderleg(model);
	initclover(model);

}

int SpiderTexture::initconeorcylindercurvedY(SpiderModel& model)
{	double prevx=0,prevy=0;
	_alpha = 4;
	_beta = 10;
	_gamma = 10;
	double Y = 4;
for (int zz = 0; zz < _legz; zz ++) {
	for (int yy = 0; yy < _legh; yy ++) {
			//_beta *= 0.9;
			Y *= 0.75;
		for (int xx = 0; xx < _legw*Y; xx ++) { 
			Point pt(xx*_alpha,yy*_beta,zz*_gamma);
			double ptx = pt.get_x()*_alpha,
				pty = pt.get_y()*_beta,
				ptz = pt.get_z()*_gamma;
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)(ptx*_alpha)%_w, (int)(pty*_beta)%_h);
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			thetax += 0.001;
			thetay += 0.001;
			thetaz += 0.001;
			Vector3 prot(ptx,pty,zz*_gamma);
			//prot = rotmz*prot;
			//prot = rotmy*prot;
			prot = rotmx*prot;
		
		//if (color != 0)//alpha channel black
			/*XDrawLine(*dpy, *w, gc,
				offsetx+(int)xx,
				offsety+(int)yy,
				offsetx+(int)xx,
				offsety+(int)yy);
			*//*XDrawLine(*dpy, *w, gc,
				offsetx+(int)prot[0],
				offsety+(int)prot[1],
				offsetx+(int)prot[0],
				offsety+(int)prot[1]);
			*/
			//model.addpoint(Point(prot[0],prot[1],prot[2],color));
			model.addpoint(Point(xx*_alpha,yy*_beta,zz*_gamma,color));
			}
		}
	}		
	return 0;
}
int SpiderTexture::initconeorcylindersinkY(SpiderModel& model)
{
	_alpha = 1;//4;
	_beta = 1;//10;
	_gamma = 1;//10;
	double X = 1;
	double Y = 10;
	for (int yy = -_legh; yy < _legh; yy ++) {
	for (int xx = -_legw; xx < _legw; xx ++) {
	for (int zz = -_legz; zz < _legz; zz ++) {
			//_beta *= 0.9;
//		for (int xx = 0; xx < _legw*Y/X; xx ++) { 
			//Point pt(1,pty,ptz);
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)(xx*X/Y)%_w, (int)(yy*X/Y)%_h);
		
			//model.addpoint(Point(prot[0],prot[1],prot[2],color));
			//model.addpoint(Point(xx*_alpha,yy*_beta,zz*_gamma,color));
			model.addpoint(Point(xx,yy,zz,color));
			}
		}
		X += 0.1;
		Y -= 0.1;
	}		
	return 0;
}
int SpiderTexture::initconeorcylindersmallpatternY(SpiderModel& model)
{
	_alpha = 1;//4;
	_beta = 1;//10;
	_gamma = 1;//10;
	double X = 1;
	double Y = 10;
	double r = 10;
	for (int yy = -_legh; yy < _legh; yy ++) {
	for (int xx = -_legw; xx < _legw; xx ++) {
	for (int zz = -_legz; zz < _legz; zz ++) {
			//_beta *= 0.9;
//		for (int xx = 0; xx < _legw*Y/X; xx ++) { 
			//Point pt(1,pty,ptz);
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)(yy*yy-r*r)%_w, (int)(xx*xx-r*r)%_h);
		
			//model.addpoint(Point(prot[0],prot[1],prot[2],color));
			//model.addpoint(Point(xx*_alpha,yy*_beta,zz*_gamma,color));
			model.addpoint(Point(xx,yy,zz,color));
			}
		}
		X += 0.1;
		Y -= 0.1;
	}		
	return 0;
}
int SpiderTexture::initconeorcylinderditherY(SpiderModel& model)
{
	_alpha = 1;//4;
	_beta = 1;//10;
	_gamma = 1;//10;
	double X = 1;
	double Y = 10;
	double r = 10;
	for (int zz = -_legz; zz < _legz; zz ++) {
	for (int yy = -_legh; yy < _legh; yy ++) {
	for (int xx = -_legw; xx < _legw*_alpha; xx ++) {
			_alpha *= 0.9;
			_beta -= 0.9;
//		for (int xx = 0; xx < _legw/X; xx ++) { 
			//Point pt(1,pty,ptz);
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)(xx*_alpha)%_w, (int)(yy*_beta)%_h);
		
			//model.addpoint(Point(prot[0],prot[1],prot[2],color));
			//model.addpoint(Point(xx*_alpha,yy*_beta,zz*_gamma,color));
			model.addpoint(Point(std::sqrt(yy*yy+zz*zz-r*r),std::sqrt(xx*xx+zz*zz-r*r),std::sqrt(yy*yy+xx*xx-r*r),color));
			}
		}
	}		
	return 0;
}
int SpiderTexture::initconeorcylinderdither2Y(SpiderModel& model)
{
	_alpha = 160;//4;
	_beta = 1;//10;
	_gamma = 1;//10;
	double X = 1;
	double Y = 10;
	double r = 10;
	for (int zz = -_legz; zz < _legz; zz ++) {
	for (int yy = -_legh; yy < _legh; yy ++) {
	for (int xx = -_legw; xx < _legw*_alpha; xx ++) {
			_alpha *= 0.9;
			//_beta -= 0.9;
			//Point pt(1,pty,ptz);
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)(xx*_alpha)%_w, (int)(yy*_beta)%_h);
		
			model.addpoint(Point(std::sqrt(yy*yy+zz*zz-r*r),std::sqrt(xx*xx+zz*zz-r*r),std::sqrt(yy*yy+xx*xx-r*r),color));
			}
		}
	}		
	return 0;
}
int SpiderTexture::initconeorcylindergrowY(SpiderModel& model)
{
	_alpha = 160;//4;
	_beta = 1;//10;
	_gamma = 1;//10;
	double X = 1;
	double Y = 10;
	double r = _legh/2;
	for (int zz = -_legz; zz < _legz; zz ++) {
	for (int yy = 0/*-_legh*/; yy < _legh/2; yy ++) {
	for (int xx = -_legw; xx < _legw*_alpha; xx ++) {
			_alpha *= 0.9;
			r /= 2;
			//_beta -= 0.9;
			//Point pt(1,pty,ptz);
			//unsigned long color = 65000;
			unsigned long color = get_xpmimage().getpixel((int)(xx*_alpha)%_w, (int)(yy*_beta)%_h);
		
			model.addpoint(Point(std::sqrt(yy*yy+zz*zz-r*r),std::sqrt(xx*xx+zz*zz-r*r),std::sqrt(yy*yy+xx*xx-r*r),color));
			}
		}
	}		
	return 0;
}
//draw a diagonal spider leg
int SpiderTexture::initspiderleg(SpiderModel& model)
{
	model.empty_points();

	double r = 10;//_legh/4;
	double fracx = _w/_legw/2;
	double fracy =_h/_legh/2;
	for (int zz = -_legz; zz < _legz; zz ++) {
	for (int yy = 0; yy < _legh; yy++/*yy += fracy*/) {
	for (int xx = -_legw; xx < _legw/**_alpha*/; xx++/*xx += fracx*/) {
			//r /= 2;
			unsigned long color = get_xpmimage().getpixel((int)(xx*fracx)%_w, (int)(yy*fracy)%_h);
	/*	
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			thetax += 0.01;
			thetay += 0.01;
			thetaz += 0.01;
			Vector3 prot(std::sqrt(yy*yy+zz*zz),yy,std::sqrt(yy*yy+xx*xx-r*r));
			prot = rotmz*prot;
			prot = rotmy*prot;
			//prot = rotmx*prot;
			Point p(prot[0],prot[1],prot[2],color);
	*/
			model.addpoint(Point(std::sqrt(yy*yy+zz*zz-r*r),yy,std::sqrt(yy*yy+xx*xx-r*r),color));
			//model.addpoint(p);
			}
		}
	}		
	return 0;
}
//draw a diagonal spider leg
int SpiderTexture::initclover(SpiderModel& model)
{
	model.empty_points();

	double r = 10;//_legh/4;
	double fracx = _w/_legw/2;
	double fracy =_h/_legh/2;
	for (int zz = -_legz; zz < _legz; zz ++) {
	for (int yy = 0; yy < _legh; yy++/*yy += fracy*/) {
	for (int xx = -_legw; xx < _legw/**_alpha*/; xx++/*xx += fracx*/) {
			//r /= 2;
			unsigned long color = get_xpmimage().getpixel((int)(xx*fracx)%_w, (int)(yy*fracy)%_h);
		
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			thetax += 0.01;
			thetay += 0.01;
			thetaz += 0.01;
			Vector3 prot(std::sqrt(yy*yy+zz*zz),yy,std::sqrt(yy*yy+xx*xx-r*r));
			prot = rotmz*prot;
			prot = rotmy*prot;
			//prot = rotmx*prot;
			Point p(prot[0],prot[1],prot[2],color);
	
			//model.addpoint(Point(std::sqrt(yy*yy+zz*zz-r*r),yy,std::sqrt(yy*yy+xx*xx-r*r),color));
			model.addpoint(p);
			}
		}
	}		
	return 0;
}
//enlarge with _alpha, _beta and rotate with thetax thetay,thetaz matrices
int SpiderTexture::rotatemodel(SpiderModel& model)
{
	model.empty_points();

	int i = 0;
	for (int yy = 0; yy < _h*_beta; yy ++) {
		for (int xx = 0; xx < _w*_alpha; xx ++) { 
			Point pt(xx/_alpha,yy/_beta,1);
			unsigned long color = get_xpmimage().getpixel((int)pt.get_x(), (int)pt.get_y());
        		Matrix3 rotmx = ray3d::rotatex(thetax);
        		Matrix3 rotmy = ray3d::rotatey(thetay);
        		Matrix3 rotmz = ray3d::rotatez(thetaz);
			thetax += 0.001;
			thetay += 0.001;
			thetaz += 0.001;
			Vector3 prot(xx,yy,1);
			//prot = rotmz*prot;
			//prot = rotmy*prot;
			prot = rotmx*prot;
			Point p(prot[0],prot[1],prot[2],color);
			if (color != 0)//alpha channel black
				model.addpoint(Point(p[0],p[1],p[2],p.get_color()));
		}
	}
	return 0;
}
}
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaTexture.h"
#include "RayMantaPolygon.h"
#include<cstdlib>

namespace ray3d {	

int Texture::draw(Display **dpy, Window *w)
{
/*	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

	const std::string filename("./post.xpm");
	//NOTE: do not draw polygon lines, rather texture in between 
	//NOTE: polygons are fixed at 4 points
	ray3d::Polygon poly;
	poly += ray3d::Point(200,200,200);
	poly += ray3d::Point(120,120,120);
	poly += ray3d::Point(20,20,20);
	poly += ray3d::Point(2,2,2);
	_polygons.push_back(poly);
	for (PolygonVector::iterator vi = _polygons.begin(); vi != _polygons.end(); vi++ ) {
			for (int i = 1; i < 5; i++) {
				Point p1((*vi)[i-1]);
				Point p2((*vi)[i]);
			
				Point p3(p1.scalex(_alpha));	
				unsigned long color = _xpmimage.getpixel(p3.get_x(), p3.get_y());
				values.foreground = color;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
        			gc = XCreateGC(*dpy, *w, valuemask, &values);
				XDrawLine(*dpy, *w, gc, p3.get_x(),p3.get_y(),p2.get_x(),p2.get_y());
			}
		}
*/		
	return 0;
}



} // namespace ray3d

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include<fstream>
#include "RayMantaTextureModel.h"
#include<cstdlib>

namespace ray3d {	

int TextureModel::draw(Display **dpy, Window *w)
{
	#define NIL (0)
  	XSetWindowAttributes attrib_create;
  	unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  	attrib_create.background_pixmap = None;
  	attrib_create.override_redirect = True;
  	attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

	XChangeWindowAttributes(*dpy,*w,create_mask,&attrib_create);
	XGCValues values;
	values.foreground = 1400;//RedPixel(*dpy, DefaultScreen(*dpy));//2048;
	values.background = 2048;
	unsigned long valuemask = GCForeground | GCBackground;
        GC gc = XCreateGC(*dpy, *w, valuemask, &values);
      	//GC gc = XCreateGC(*dpy, *w, 0, NIL);

	//NOTE: do not draw polygon lines, rather texture in between 
	for (std::vector<Point>::iterator vi = _points.begin(); vi != _points.end(); vi++ ) {
		XDrawLine(*dpy, *w, gc, (*vi).get_x(),(*vi).get_y(),(*vi).get_x(),(*vi).get_y());

	}
	return 0;
}



} // namespace ray3d

/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
//local
#include "RayMantaWindow.h"
#include "RayMantaPoint.h"
#include <iostream>
#include <cmath>

RayMantaWindow::RayMantaWindow ()
{}

RayMantaWindow::RayMantaWindow(Display **dpy, Window& w, Window& title) 
{
  printf("creating RayMantaWindow..\n");
  created = False;
 frame.x = 40;//attrib.x;
  frame.y = 40;//attrib.y;
  frame.width = 320;//attrib.width;
  frame.height = 200;//attrib.height;
  frame.border_width = 3;//attrib.border_width;
  frame.window = w;
  frame.title = title;
  title_y = 20; //height of the title frame
  lowerborder_y = 7; //height of the lower border

  /*frame.window = createTopLevelWindow(frame.x, frame.y, frame.width,\
				      frame.height + title_y + lowerborder_y,\
  				      frame.border_width);
  */ //XRaiseWindow(*dpy, frame.application_window);
  //XMapWindow(*dpy, frame.window);
  XMapWindow(*dpy, w);
//  //  XMapSubwindows(*dpy, frame.application_window);
//  XMapSubwindows(*dpy, frame.window);
  
//  XMapSubwindows(*dpy, frame.title);
  
//  XUngrabServer(*dpy); 
//   decorate_title();
  	XFlush(*dpy);
//	sleep(10);
 /* 
  Pixel back_pix, fore_pix;
  back_pix = GetColor("black");
  fore_pix = GetColor("darkcyan");
  
  unsigned long gc_mask = 0;
  gc_mask = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
  XGCValues values;
  values.foreground = fore_pix;
  values.background = back_pix;
  values.graphics_exposures = True;
  //values.function = GXcopy|GXand;
  values.line_width = 3;
  gc = XCreateGC(*dpy, pixie.getRootWindow(), gc_mask, &values);
  //XChangeGC(*dpy, gc, gc_mask, &values); //overbodig?
  //XSetFillStyle(*dpy, gc, FillSolid);
  XSetClipOrigin(*dpy, gc, 0, 0);
  XSetClipMask(*dpy, gc, None);
  XFillRectangle(*dpy, pixie.getRootWindow(), gc, 0,0,50,50);
  //XDrawRectangle(*dpy, pixie.getRootWindow(), gc, 0,0,200,200);
  //XFillRectangle(*dpy, pixie.getRootWindow(), gc, 0,0,50,50);
*/
/*#define NIL (0)
 gc = XCreateGC(0,w,0,NIL);
//XSetForeground(0,gc,whiteColor);
//XDrawLine(0,w,gc,10,60,180,20);
XFlush(0);
//sleep(10);
*/
}

RayMantaWindow::~RayMantaWindow()
{
  //XDestroyWindow(*dpy, frame.title);
  //XDestroyWindow(*dpy, frame.application_window);
  //XDestroyWindow(*dpy, window);
//  XDestroyWindow(*dpy, frame.window);//destroys subwindows
  printf("RayMantaWindow destroyed.\n");
}
void RayMantaWindow::drawsphere(Window const& w)
{
 /* for (int xx = 0; xx < 200; xx++) {
	for (int yy = 0; yy < 200; yy++) {

  double r = 4;
  ray3d::Point s(xx,yy,0);
  ray3d::Point center(10,10,10); 
  ray3d::Point v = s - center; 
  ray3d::Point d(7,7,7);
  //double t = (2*v*d + std::sqrt(2*v*d-4(v*v-r*r))/2 
  double t1 = - (v*d) - std::sqrt((v*d)*(v*d) - (v*v - r*r));
  double t2 = - (v*d) + std::sqrt((v*d)*(v*d) - (v*v - r*r));


  if (t1 > 0 && t2 > 0) {
  std::cout<< "--->"<<t1<<t2<<std::endl;
#define NIL (0)
        gc = XCreateGC(*dpy, w, 0, NIL);
      XDrawLine(*dpy, w, gc, 10, 60, 180, 20);
  //	XDrawLine(*dpy, pixie.getRootWindow(), gc, 0,0,t1,t2);
	}
	}
	}
*/
}

void RayMantaWindow::drawline(Window const& w, int x1, int y1, int x2 ,int y2)
{
/*
      int blackColor = BlackPixel(*dpy, DefaultScreen(*dpy));
      int whiteColor = WhitePixel(*dpy, DefaultScreen(*dpy));
      XSelectInput(*dpy, w, StructureNotifyMask);

      // "Map" the window (that is, make it appear on the screen)

      XMapWindow(*dpy, w);

      // Create a "Graphics Context"
#define NIL (0)
      GC gc = XCreateGC(*dpy, w, 0, NIL);

      // Tell the GC we draw using the white color

      XSetForeground(*dpy, gc, whiteColor);

      // Wait for the MapNotify event

      for(;;) {
	    XEvent e;
	    XNextEvent(*dpy, &e);
	    if (e.type == MapNotify)
		  break;
      }

      // Draw the line
      
      XDrawLine(*dpy, w, gc, 10, 20, 10, 200);

      // Send the "DrawLine" request to the server

      XFlush(*dpy);
*/
}


Window RayMantaWindow::createTopLevelWindow(int x, int y, unsigned int width,\
				   unsigned int height,\
				   unsigned int borderwidth,Window *w)
{
/*  XSetWindowAttributes attrib_create;
  unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  attrib_create.background_pixmap = None;
  attrib_create.override_redirect = True;
  attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;

  *w =  (XCreateWindow(*dpy, pixie.getRootWindow(), x, y, 
			width, height,
			borderwidth, pixie.getDepth(), InputOutput,
			pixie.getVisual(), create_mask,
			&attrib_create));
   return *w;
*/
}

Window RayMantaWindow::createTopLevelSimpleWindow(int x, int y, unsigned int width,\
				   unsigned int height,\
				   unsigned int borderwidth)
{
 /* XSetWindowAttributes attrib_create;
  unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWOverrideRedirect | CWEventMask;

  attrib_create.background_pixmap = None;
  attrib_create.override_redirect = True;
  attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | EnterWindowMask;
      int blackColor = BlackPixel(*dpy, DefaultScreen(*dpy));
      int whiteColor = WhitePixel(*dpy, DefaultScreen(*dpy));
      Window w = XCreateSimpleWindow(*dpy, DefaultRootWindow(*dpy), 0, 0, 
				     200, 100, 0, blackColor, blackColor);
	return w;
*/
}

Window RayMantaWindow::createChildWindow(Window parent, Cursor cursor) 
{
/*  XSetWindowAttributes attrib_create;
  unsigned long create_mask = CWBackPixmap | CWBorderPixel |
                              CWEventMask;

  attrib_create.background_pixmap = None;
  attrib_create.event_mask = ButtonPressMask | ButtonReleaseMask |
                             ButtonMotionMask | ExposureMask |
                             EnterWindowMask | LeaveWindowMask;

  if (cursor) {
    create_mask |= CWCursor;
    attrib_create.cursor = cursor;
  }

  return (XCreateWindow(*dpy, parent, 0, 0, 1, 1, 0,
			pixie.getDepth(), InputOutput, pixie.getVisual(),
			create_mask, &attrib_create));
*/
}

void RayMantaWindow::decorate_title() 
{
/*  unsigned long valuemask = *//*GCFunction;*//*GCForeground | GCBackground | GCGraphicsExposures;
  XGCValues values;
  //Pixel f_pix, b_pix;
  //values.function = GXxor;    
  //GC gc = XCreateGC(*dpy, pixie.getRootWindow(),valuemask, &values); 
  gc = XCreateGC(*dpy, frame.window,rootwin,valuemask, &values); 
  

  //RayMantaImage * pix = new RayMantaImage ("/usr/X11R6/include/X11/pixmaps/mini-eyes.xpm", 
  //			   (Drawable)frame.title, gc);


  //new RayMantaImage("/home/johan/mutt.xpm", pixie.getRootWindow());
  //XSetClipOrigin(*dpy,gc,frame.x, frame.y);
  //XSetClipMask(*dpy, gc,None);// pix->pixmap);  
  //XFillRectangle(*dpy, frame.title, gc, 0,0,50,50);
  XDrawLine(*dpy, frame.window, gc, 0,0, frame.width, 0);
  XDrawLine(*dpy, frame.window, gc, frame.width-1,0,frame.width-1,title_y);
  char **argv;
  int argc;
  if (XGetCommand(*dpy, window, &argv, &argc))
    {
  */    /*
	int i;
	char **fonts = XListFonts(*dpy, "helvetica", 100, &i);
	for (int j = 0; j<100; j++)
	printf("%s ", fonts[j]);
      */
   /*   //XFontSet fs = pixie.createFontSet();
      Pixel back_pix, fore_pix;
      back_pix = GetColor((char *)"black");
      fore_pix = GetColor((char *)"black");
      
      unsigned long gc_mask = 0;
      gc_mask = GCForeground|GCBackground|GCGraphicsExposures|GCLineWidth;
      XGCValues values;
      values.foreground = fore_pix;
      values.background = back_pix;
      values.graphics_exposures = True;
      //values.function = GXcopy|GXand;
      values.line_width = 3;
      XChangeGC(*dpy, gc, gc_mask, &values);
      XmbDrawString(*dpy, frame.title, pixie.getFontSet(), gc, 10, 15, argv[0], strlen(argv[0]));
      back_pix = GetColor((char *)"black");
      fore_pix = GetColor((char *)"darkcyan");
      
      values.foreground = fore_pix;
      values.background = back_pix;
      XChangeGC(*dpy, gc, gc_mask, &values);
  XDrawLine(*dpy, frame.window, gc, 0,0, 30, 30);
    }
*/
}

//remove this and use the pixie.getcolor
Pixel RayMantaWindow::GetColor(Display **dpy, char *name)
{
  XColor color;
  XWindowAttributes attributes;

  Window root_window = RootWindow(*dpy, DefaultScreen(*dpy));
  XGetWindowAttributes(*dpy,root_window,&attributes);
  color.pixel = 0;
   if (!XParseColor (*dpy, attributes.colormap, name, &color)) 
     {
       printf("parse no color");
     }
   else if(!XAllocColor (*dpy, attributes.colormap, &color)) 
     {
       printf("parse no color");
     }
  return color.pixel;
}

void RayMantaWindow::destroy(Display **dpy) 
  //first unmap then destroy after the unmap event
{
  // XDestroyWindow(*dpy, frame.window);
  //XSelectInput(*dpy, window, NoEventMask);
  XUnmapWindow(*dpy, frame.window); //unmaps subwindows
  //XFlush(*dpy);test
  //XUnmapSubwindows(*dpy, frame.window);
  delete this;
}

void RayMantaWindow::unmap(Display **dpy)
{
  //XGrabServer(*dpy); //This bugs some apps
  //the next could break since wins are referenced after during destroy
  // XSelectInput(*dpy, window, NoEventMask);
  //XSelectInput(*dpy, frame.window, NoEventMask); //redundant
  //XSetWindowAttributes attrib;
  
  XUnmapWindow(*dpy, frame.window);
  //XUnmapWindow(*dpy, frame.title);
  //  XUnmapWindow(*dpy, window);
  XFlush(*dpy);
  //delete this; This bugs apps (gv) i.e. the parent unmapped while a little wondow takes care of the user 
  //XUngrabServer(*dpy);
}

void RayMantaWindow::resize(Display **dpy, int x, int y)
{
  frame.width = frame.width-x;
  frame.height = frame.height-y;
  XResizeWindow(*dpy, frame.window, frame.width, frame.height + lowerborder_y + title_y);
  XResizeWindow(*dpy, window, frame.width, frame.height);
  XResizeWindow(*dpy, frame.title, frame.width, title_y);	      
  XResizeWindow(*dpy, frame.lowerborder, frame.width, lowerborder_y);
  XReparentWindow(*dpy, frame.lowerborder, frame.window, 0, frame.height+title_y);
 // XReparentWindow(*dpy, frame.destroy, frame.title, frame.width-title_y, 5);
  decorate_title();
}

void RayMantaWindow::configure(Display **dpy, XConfigureRequestEvent xcr)
{
  //if (xcr.window == window) //only the client window should get configurerequest
  //{
      frame.x = xcr.x;
      frame.y = xcr.y;
      frame.width = xcr.width;
      frame.height = xcr.height;
      XResizeWindow(*dpy, window, frame.width, frame.height);
      XMoveResizeWindow(*dpy, frame.window, frame.x, frame.y, frame.width, frame.height+title_y+lowerborder_y); //--FIXME This moves too no check for x,y =(0,0) or something!
      XResizeWindow(*dpy, frame.title, frame.width, title_y);
      XResizeWindow(*dpy, frame.lowerborder, frame.width, lowerborder_y);
      XReparentWindow(*dpy, frame.lowerborder, frame.window, 0, frame.height+title_y);
      decorate_title();
      //    }
}

void RayMantaWindow::expose(XExposeEvent& xe)
{/*
  if (xe.window == frame.title)
    {
      decorate_title();
      frame.x_root = xe.x;
   */   frame.y_root = xe.y;
      printf("RayMantaWindow expose\n");
     /* 
      if (!created)
	{
	  //pixie.positionWindow(this);
	  created = True;
	}
      
    }*/
  /* this doesnt' do anything apparently only title and lowerborder get expose events
     else if (xe.window == frame.window && !created)//last window created maybe
     {
     pixie.positionWindow(this);
     }*/
}

void RayMantaWindow::move(Display **dpy, int new_x, int new_y)
{
  XMoveWindow(*dpy, frame.window, new_x, new_y);
  frame.x = new_x;
  frame.y = new_y;
}

void RayMantaWindow::buttonpress()
{
  
}

void RayMantaWindow::motion()
{

}
/*
 Copyright (C) Johan Ceuppens 2011

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional> 
#include <iostream> 
#include <unistd.h> 
#include <signal.h> 
#include <cstdlib> 
#include <cstring> 
#include "RayMantaXNet.h"

#include "../xlua/xlua.h"
#include "../xlua/xluacode.h"

inline void signalforkfunc(int) {

	//auto unpause
}

template <class S,class T>
int RayMantaXNet<S,T>::fork(S const& loadfilename, S const& parsefilename, int const& wordid)
{

	std::map<int , T> m;
	loadXkeywords(KeyWords<S,T>());
	T buf;
	
	std::cout<<"parsing...(non-empty)"<<std::endl;
	XLUA::Xlua<std::string,std::string> xl = XLUA::Xlua<std::string,std::string>();
	xl.load();
	xl.loadfile(loadfilename);
	//L = lua_open();
	//if (luaL_dofile(L,NULL)!=0) fprintf(stderr, "%s\n", lua_tostring(L,-1));
}

template <class S, class T>
int RayMantaXNet<S,T>::loadXkeywords(KeyWords<S,T> const& kw)
{
        const_cast<KeyWords<S,T>& >(kw).add(::strdup("p:creat"));//p:create is a process creation keyword for xlua not lua itself

        keywords = kw;

        return 0;
}



template class RayMantaXNet<std::string, void *>;
//local
#include "WindowManager.h"
#include "RayManta.h"
#include "RayMantaWindow.h"

WindowManager::WindowManager() 
{
  unsigned int nchildren;
  Window win, root, parent, *children;
/*  Display *display = XOpenDisplay(dpy_name);
  if (!display) 
    {
      printf("error connecting to X server\n");
      exit(0);
    }
*//*  if ((XQueryTree(display, RootWindow(display, DefaultScreen(display)), &root, &parent, 
	     &children, &nchildren)) == 0)
    {
      printf("XQueryTree failed.\n");
    }
 */ // printf("children = %d\n", (int)nchildren);
/*  for (int i = 0; i < (int) nchildren; i++)
    {
      if (children[i] == None) 
	continue;
           
      XWindowAttributes attrib;
      if (XGetWindowAttributes(pixie.getDisplay(), children[i], &attrib)) 
	{
	  if (attrib.override_redirect) //ignore overrides
	    continue; 
	  if (attrib.map_state != IsUnmapped)  
	    {
	      new RayMantaWindow(children[i]);
	    }
	}
    }
*/  //  XMapWindow(display, RootWindow(display, DefaultScreen(display)));
  printf("made windowmanager\n");
}

WindowManager::~WindowManager()
{
}


#include "RayManta.h"
#include "Xmanager.h"

Xmanager::Xmanager()
{}

void Xmanager::init(DisplayBase<Display **>& dpyb)
{
  long event_mask;

  root_window = RootWindow(*(dpyb.get_display()), DefaultScreen(*(dpyb.get_display())));
  depth = DefaultDepth(*(dpyb.get_display()), DefaultScreen(*(dpyb.get_display())));
  visual = DefaultVisual(*(dpyb.get_display()), DefaultScreen(*(dpyb.get_display())));
  screen = DefaultScreen(*(dpyb.get_display()));
  //XSetErrorHandler((XErrorHandler) handleXErrors);

/*  //XGrabServer(*(dpyb.get_display()));
  //XrmInitialize();
  //XSynchronize(*(dpyb.get_display()), False);
  //XSync(*(dpyb.get_display()), False);
  //XUngrabServer(*(dpyb.get_display()));
  //XCreateSimpleWindow(*(dpyb.get_display()), XRootWindow(*(dpyb.get_display()) , DefaultScreen(*(dpyb.get_display()))), 0,0,1280,1024, 0, 0,0);
  event_mask = ButtonPressMask | ButtonReleaseMask |
    ColormapChangeMask | EnterWindowMask | PropertyChangeMask | 
    SubstructureRedirectMask | KeyPressMask | KeyReleaseMask;
  XSelectInput(*(dpyb.get_display()), root_window, event_mask);
  Cursor cursor;
  Pixmap pixmap_cursor, mask_cursor;
  XpmAttributes xpm_attrib;
  xpm_attrib.valuemask = XpmExactColors|XpmCloseness|XpmDepth;
  xpm_attrib.exactColors = False;
  xpm_attrib.closeness = 40000;
  xpm_attrib.depth = 1;
  
  if (0 == XpmReadFileToPixmap(*(dpyb.get_display()), root_window,
			       "/usr/X11R6/include/X11/pixmaps/mini-x.xpm",
			       &pixmap_cursor,&mask_cursor,&xpm_attrib)) 
    {
      XColor  closest, exact, closest2, exact2;
      int status;
      status = XAllocNamedColor(*(dpyb.get_display()), 
				DefaultColormap(*(dpyb.get_display()), DefaultScreen(*(dpyb.get_display()))), 
				"black", &exact, &closest);
      XAllocNamedColor(*(dpyb.get_display()), DefaultColormap(*(dpyb.get_display()), DefaultScreen(*(dpyb.get_display()))),
		       "lightgreen", &exact2, &closest2);
      if (status == 0) { printf("failed to alloc color\n");}
  
      cursor = XCreatePixmapCursor(*(dpyb.get_display()), pixmap_cursor,
					  mask_cursor, &closest,
					  &closest2, 0,0);
      XDefineCursor(*(dpyb.get_display()), root_window, cursor);//global cursor set
    }
  else 
    {
      printf("cursor pixmap failed.\n");
    }
  */
  printf("made xmanager\n");
}

Xmanager::~Xmanager()
{

}

static const char *getFontElement(const char *pattern, char *buf, int bufsiz, ...) {
  const char *p, *v;
  char *p2;
  va_list va;

  va_start(va, bufsiz);
  buf[bufsiz-1] = 0;
  buf[bufsiz-2] = '*';
  while((v = va_arg(va, char *)) != NULL) {
    p = strcasestr(pattern, v);
    if (p) {
      strncpy(buf, p+1, bufsiz-2);
      p2 = strchr(buf, '-');
      if (p2) *p2=0;
      va_end(va);
      return p;
    }
  }
  va_end(va);
  strncpy(buf, "*", bufsiz);
  return NULL;
}

static const char *getFontSize(const char *pattern, int *size) {
  const char *p;
  const char *p2=NULL;
  int n=0;

  for (p=pattern; 1; p++) {
    if (!*p) {
      if (p2!=NULL && n>1 && n<72) {
	*size = n; return p2+1;
      } else {
	*size = 16; return NULL;
      }
    } else if (*p=='-') {
      if (n>1 && n<72 && p2!=NULL) {
	*size = n;
	return p2+1;
      }
      p2=p; n=0;
    } else if (*p>='0' && *p<='9' && p2!=NULL) {
      n *= 10;
      n += *p-'0';
    } else {
      p2=NULL; n=0;
    }
  }
}

XFontSet Xmanager::createFontSet(DisplayBase<Display **>& dpyb)
{
  const char *fontname = "fixed";
#define   FONT_ELEMENT_SIZE 50
  XFontSet fs;
  char **missing;
  char *def = (char *)"-";
  int nmissing, pixel_size = 0, buf_size = 0;
  char weight[FONT_ELEMENT_SIZE], slant[FONT_ELEMENT_SIZE];

  fs = XCreateFontSet(*(dpyb.get_display()),
		      fontname, &missing, &nmissing, &def);
  if (fs && (! nmissing)) return fs;
  
#ifdef    HAVE_SETLOCALE
  if (! fs) {
    if (nmissing) XFreeStringList(missing);

    setlocale(LC_CTYPE, "C");
    fs = XCreateFontSet(*(dpyb.get_display()), fontname,
			&missing, &nmissing, &def);
    setlocale(LC_CTYPE, "");
  }
#endif // HAVE_SETLOCALE

  if (fs) {
    XFontStruct **fontstructs;
    char **fontnames;
    XFontsOfFontSet(fs, &fontstructs, &fontnames);
    fontname = fontnames[0];
  }

  getFontElement(fontname, weight, FONT_ELEMENT_SIZE,
		 "-medium-", "-bold-", "-demibold-", "-regular-", NULL);
  getFontElement(fontname, slant, FONT_ELEMENT_SIZE,
		 "-r-", "-i-", "-o-", "-ri-", "-ro-", NULL);
  getFontSize(fontname, &pixel_size);

  if (! strcmp(weight, "*")) strncpy(weight, "medium", FONT_ELEMENT_SIZE);
  if (! strcmp(slant, "*")) strncpy(slant, "r", FONT_ELEMENT_SIZE);
  if (pixel_size < 3) pixel_size = 3;
  else if (pixel_size > 97) pixel_size = 97;

  buf_size = strlen(fontname) + (FONT_ELEMENT_SIZE * 2) + 64;
  char *pattern2 = new char[buf_size];
  snprintf(pattern2, buf_size - 1,
	   "%s,"
	   "-*-*-%s-%s-*-*-%d-*-*-*-*-*-*-*,"
	   "-*-*-*-*-*-*-%d-*-*-*-*-*-*-*,*",
	   fontname, weight, slant, pixel_size, pixel_size);
  fontname = pattern2;

  if (nmissing) XFreeStringList(missing);
  if (fs) XFreeFontSet(*(dpyb.get_display()), fs);

  fs = XCreateFontSet(*(dpyb.get_display()), fontname,
		      &missing, &nmissing, &def);
  delete [] pattern2;

  return fs;
}
.SUFFIXES : .o .cc .c

CC = g++
CFLAGS = -g
INCLUDES = -I/usr/X11R6/include
LIBS = -L/usr/X11R6/lib -lX11 -lXpm -lXext -lpthread -L./lib -llua -L./xlua -lxlua -L./raymanta -lraymanta
# -ljpeg -lpng -L./widget -lPixieWidget -lImlib
###OBJS = RayMantaWindow.o WindowManager.o  Xmanager.o RayMantaImage.o RayMantaPoint.o RayMantaMatrix.o RayMantaMatrix3.o RayMantaMatrix4.o RayMantaNet.o RayMantaNetPthread.o RayMantaGA.o RayMantaNetMarkov2.o Boltzman.o RayMantaEngine.o RayMantaModel.o RayMantaSphereModel.o RayMantaPolygon.o RayMantaPolygonModel.o RayMantaImageBase.o RayMantaPixmapImage.o RayMantaTextureModel.o RayMantaPixmapTextureModel.o RayMantaTexture.o RayMantaPixmapTexture.o RayMantaBaseVisit.o RayMantaXNet.o keywords.o RayMantaPixmapTextureModelFill.o RayMantaPixmapTextureModelRotate.o RayMantaSpiderTexture.o RayMantaSpiderModel.o

###FIXME add RayMantaNetMarkov.o

###FIXME RayManta: debug xlua $(OBJS) main.o
all: RayManta RayMantaRayTracer RayMantaProducerSystem

RayManta: debug xlua raymanta $(OBJS) main.o
###	@echo "***COMPILER NOTE*** Please include RayMantaNetMarkov.o inside this Makefile for Markov networking (RayMantaNetMarkov2.o is already included.)"
	$(CC) $(CFLAGS) $(INCLUDES) $(OBJS) -o xmantaray  $(LIBS) main.o

RayMantaRayTracer: debug xlua raymanta $(OBJS) mainray.o
###	@echo "***COMPILER NOTE*** Please include RayMantaNetMarkov.o inside this Makefile for Markov networking (RayMantaNetMarkov2.o is already included.)"
	$(CC) $(CFLAGS) $(INCLUDES) $(OBJS) -o xmantaraytracer  $(LIBS) mainray.o

RayMantaProducerSystem: debug xlua raymanta $(OBJS) mainproducer.o
###	@echo "***COMPILER NOTE*** Please include RayMantaNetMarkov.o inside this Makefile for Markov networking (RayMantaNetMarkov2.o is already included.)"
	$(CC) $(CFLAGS) $(INCLUDES) $(OBJS) -o xmantarayproducer  $(LIBS) mainproducer.o

debug:
	@echo Constructing config.h
	@rm -f config.h
	@echo '#define	DEBUG' >> config.h
	@echo "***COMPILER NOTE*** The liblua path and link might have to be changed to your liblua install path. There is a liblua.a library inside ./lib which you can overwrite."

raymanta : $(OBJS) 
	cd raymanta; $(MAKE) $(MFLAGS)

xlua : $(OBJS) 
	cd xlua; $(MAKE) $(MFLAGS)

test : $(OBJS) 
	cd test; $(MAKE) $(MFLAGS)

clean: 
	rm *.o xmantaray xmantaraytracer xmantarayproducer config.h ./xlua/*.o ./xlua/*.so ./xlua/*.a ./test/*.so ./test/*.o ./test/test1 ./raymanta/*.o ./raymanta/*.a ./raymanta/*.so *.o ./files3d/3ds/*/*.o ./files3d/3ds/*.a ./files3d/3ds/*.o ;

.cpp.o:
	$(CXX) $(CFLAGS) $< -o $@

.cc.o :
	$(CC) $(CFLAGS) $(INLCUDES) -c $<
.SUFFIXES : .o .cc .c

CC = g++
CFLAGS = -g
INCLUDES = -I/usr/X11R6/include
LIBS = -L/usr/X11R6/lib -lX11 -lXpm -lXext -lpthread -L./lib -llua -L./xlua -lxlua
# -ljpeg -lpng -L./widget -lPixieWidget -lImlib
OBJS = RayMantaWindow.o WindowManager.o  Xmanager.o RayMantaImage.o RayMantaPoint.o RayMantaMatrix.o RayMantaMatrix3.o RayMantaMatrix4.o RayMantaNet.o RayMantaNetPthread.o RayMantaGA.o RayMantaNetMarkov2.o Boltzman.o RayMantaEngine.o RayMantaModel.o RayMantaSphereModel.o RayMantaPolygon.o RayMantaPolygonModel.o RayMantaImageBase.o RayMantaPixmapImage.o RayMantaTextureModel.o RayMantaPixmapTextureModel.o RayMantaTexture.o RayMantaPixmapTexture.o RayMantaBaseVisit.o RayMantaXNet.o keywords.o RayMantaPixmapTextureModelFill.o RayMantaPixmapTextureModelRotate.o RayMantaSpiderTexture.o RayMantaSpiderModel.o RayManta.o RayMantaRayTracer.o RayMantaProducerSystem.o

###FIXME add RayMantaNetMarkov.o

###FIXME RayManta: debug xlua $(OBJS) main.o
all: RayManta

RayManta: $(OBJS)
	@echo "***COMPILER NOTE*** Please include RayMantaNetMarkov.o inside this Makefile for Markov networking (RayMantaNetMarkov2.o is mainstream included.)"
	ar rcu libraymanta.a *.o
	ranlib libraymanta.a
###	$(CC) $(CFLAGS) $(INCLUDES) $(OBJS) -o xmantaray  $(LIBS) main.o RayManta.o

clean: 
	rm *.o libraymanta.a xmantaray xmantaraytracer config.h ./xlua/*.o ./xlua/*.so ./xlua/*.a ./test/*.so ./test/*.o ./test/test1;

.cpp.o:
	$(CXX) $(CFLAGS) $< -o $@

.cc.o :
	$(CC) $(CFLAGS) $(INLCUDES) -c $<
#include "3ds/3ds.h"
#include<iostream>
#include<vector>
int main()
{
Scene3DS *scene = new Scene3DS("./exmaple.3ds");
/* then you simply read the data (it is automatically
parsed above */

// reading the meshes
std::vector<Mesh3DSObject> meshes = scene->Meshes();

// reading the vertices
// assuming theres at least one mesh in scene
//std::vector<Mesh3DSVertex> vertices = meshes[0];
//std::cout << "(" << vertices[0].x << ","
//<< vertices[0].y << ","
//<< vertices[0].z << ")\n";

// reading the faces
//std::vector<Mesh3DSFace> faces = scene->Faces();
// 3ds files store faces as having 3 indexs in vertex arrays
//Mesh3DSFace first_face = faces[0];

// first vertex of first_face
//Mesh3DSVertex a = vertices[first_face.a]
//Mesh3DSVertex b = vertices[first_face.b]
//Mesh3DSVertex c = vertices[first_face.c]
}

#include "chunk/file.h"
#include "chunk/chunk.h"

#include "scene3ds.h"
#ifndef SCENE3DS_H
#define SCENE3DS_H

#include <string>

#include "light/light3ds.h"
#include "material/material3ds.h"
#include "mesh/mesh3ds.h"

/***/
class Scene3DS : public Light3DS , public Material3DS , public Mesh3DS
{
    public:
	/***/
	Scene3DS(const char *src);
	/***/
	Scene3DS(const std::string &src);
	/***/
	~Scene3DS();

	void operator=(const char *src);
    private:
	
	void ParseEditor3D(Model3DSChunk c);
	void ParseEditObject(Model3DSChunk c);
};

#endif
#include "scene3ds.h"

#include <iostream>
using namespace std;

#include "chunk/file.h"
#include "chunk/chunk.h"

Scene3DS::Scene3DS(const char *src)
{
	operator=(src);
}
Scene3DS::Scene3DS(const string &src)
{
	operator=(src.c_str());
}
Scene3DS::~Scene3DS()
{
}

void Scene3DS::operator=(const char *src)
{
	Model3DSFile file(src);

	Model3DSChunk root = file.Child();

	for(Model3DSChunk cc = root.Child() ; cc ; cc = cc.Sibling())
	{
		switch(cc.ID())
		{
			case(0x0002):
				// parse int which has version info
			break;
			
			case(0x3d3d):
				ParseEditor3D(cc);
			break;

			default:
			break;
		}
	}
}

void Scene3DS::ParseEditor3D(Model3DSChunk c)
{
	for(Model3DSChunk cc = c.Child() ; cc ; cc = cc.Sibling())
	{
		switch(cc.ID())
		{
			case(0x3d3e):
				// mesh version
			break;

			case(0xafff):
				Material3DS::Parse(cc);
			break;
			
			case(0x4000):
				ParseEditObject(cc);
			break;
			
			default:
			break;
		}
	}
}

void Scene3DS::ParseEditObject(Model3DSChunk c)
{
	string obj_name = c.Str();
	
	for(Model3DSChunk cc = c.Child() ; cc ; cc = cc.Sibling())
	{
		switch(cc.ID())
		{
			case(0x4100):
				Mesh3DS::Parse(obj_name , cc);
			break;
			
			case(0x4600):
				Light3DS::Parse(obj_name , cc);
			break;
			
			case(0x4700):
				cout << "\tobject camera\n";
			break;
			
			default:
				cout << "\terror : unknown object "
					<< hex << cc.ID() << dec << "\n";
			break;
		}
	}
}

\end{verbatim}
\end{mylisting}


\section{\large Conclusion}


\bibliographystyle{plain}
\bibliography{refs} % refs.bib

\end{document}

